commit 2e695749437e7f64a5e2f007f3a52121ae230fe6 Author: Joren Date: Thu Nov 26 15:11:41 2026 +0100 first commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d629982 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +/applesync +/applesync.toml +*.report.json +applesync-report.json diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..688db04 --- /dev/null +++ b/Makefile @@ -0,0 +1,18 @@ +BINARY := applesync + +.PHONY: build test vet fmt clean + +build: + go build -o $(BINARY) ./cmd/applesync + +test: + go test ./... + +vet: + go vet ./... + +fmt: + gofmt -w cmd internal + +clean: + rm -f $(BINARY) diff --git a/README.md b/README.md new file mode 100644 index 0000000..bdb3945 --- /dev/null +++ b/README.md @@ -0,0 +1,159 @@ +# AppleSync + +Sync public Apple Music playlists into a Qobuz library and generate m3u +playlists. + +AppleSync: + +1. reads public Apple Music playlist URLs from a TOML config, +2. fetches every track in playlist order (no Apple ID or developer token needed), +3. groups the tracks by Apple album and looks each album up on Qobuz + (UPC first, then artist/title fuzzy matching, verified by ISRC), +4. downloads the full matched albums with the existing `rip` (streamrip-go) + binary, using rip's own Qobuz login, quality and download database, +5. scans the downloaded files and writes an extended m3u containing exactly the + playlist tracks, in playlist order. + +The m3u references the ripped album files; AppleSync does not copy audio files. + +## Requirements + +- Go 1.24+ to build. +- `rip` (streamrip-go) installed and logged into Qobuz on the same host. +- A Qobuz subscription that allows the configured quality. +- Optional: beets 2.x with an existing library. Recommended on large libraries; + AppleSync queries beets by ISRC and album title instead of walking every + directory, and gets the canonical imported file paths. +- Public Apple Music playlists (`pl.…`). Private `/library/` playlists are not + supported. + +## Build + +```sh +make build +# or +go build -o applesync ./cmd/applesync +``` + +## Configuration + +Copy `applesync.example.toml` to `applesync.toml` and edit the paths and +playlists. The example targets `pihole@jirachi`: + +- downloads (rip's staging area): `/home/pihole/music/Full/QOBUZ_MONITOR` +- final library: `/home/pihole/music/Full` +- playlists: `/home/pihole/music/Full/Qobuz/Playlists` + +`library_dir` is the root the music server sees, including beets/imported +folders like `Full/Otta/ASTRA/06 STRANGER.flac`. AppleSync prefers files there +and falls back to `downloads_dir` for albums that have not been imported yet. +If `library_dir` is omitted it defaults to `downloads_dir`. + +### Beets + +With beets enabled, AppleSync runs one or two `beet ls` queries per sync (by +ISRC and by album title) and uses the returned paths/ISRCs as its library +index. It then scans only `downloads_dir` for albums that have not been imported +yet. If beets is disabled, missing, or fails, AppleSync falls back to scanning +`library_dir`. + +```toml +[beets] +enabled = true +binary = "/home/pihole/.local/bin/beet" +``` + +Use absolute paths for `rip` and `beet` so cron jobs work without a login shell. + +Per playlist, `mode` controls only the m3u: + +- `replace` — rebuild the file to contain exactly the playlist tracks. +- `append` — keep existing entries and append only tracks whose files are not + already listed. Re-running is a no-op. + +Downloads are always additive: rip's download database skips albums that are +already present. Use `--force` to redownload. + +### Qobuz app id + +Qobuz album search needs only the public app id. AppleSync resolves it in this +order: + +1. `[qobuz].app_id` from the config, +2. the `app_id` already bootstrapped into rip's config, +3. scraping `play.qobuz.com`. + +No Qobuz password or user token is stored by AppleSync. + +## Usage + +```sh +# Match everything and show what would happen (no downloads, no m3u writes) +./applesync sync --dry-run -v + +# Full sync with the default config path (./applesync.toml) +./applesync sync + +# Only one playlist, append mode +./applesync sync --playlist "indie" --mode append + +# Rebuild m3u files from files that are already downloaded +./applesync sync --skip-download + +# Ignore cached (including negative) Qobuz matches and look everything up again +./applesync sync --refresh-matches + +# Download only the first 3 missing albums (useful for a first test) +./applesync sync --limit-albums 3 + +# Write a JSON report +./applesync sync --report applesync-report.json +``` + +`--playlist` matches against the configured name and URL and can be repeated. + +## How files are resolved + +If beets is enabled (recommended), AppleSync runs `beet ls` once for the +playlist ISRCs and once for the album titles. That returns the canonical paths +and ISRCs of imported files without walking the library. It then scans only +`downloads_dir` for albums that have not been imported yet. + +Without beets, AppleSync scans the album folders under `library_dir` and +`downloads_dir` and reads tags with `github.com/dhowden/tag`. + +Tracks are matched by: + +1. exact ISRC (rip writes ISRC tags; beets stores them too), +2. normalized artist + title, +3. title restricted to the matched album and a matching artist. + +Files in `library_dir` that are outside `downloads_dir` (the imported copies) +are preferred over rip's staging copies. AppleSync never modifies the beets +library; it only queries it. If a newly ripped album has not been imported yet, +the m3u points into `downloads_dir`; a later run updates it to the imported path. + +## Missing tracks + +By default (`missing = "warn"`) AppleSync writes all tracks it found and reports +the rest in the summary and optional JSON report. Set `missing = "fail"` to +leave a playlist's m3u untouched when anything is missing. Tracks that are not +on Qobuz yet (common for new singles) are skipped; the next run retries the +negative match after a week. + +## Cron + +```cron +15 5 * * * /home/pihole/.local/bin/applesync sync --config /home/pihole/.config/applesync/config.toml >> /home/pihole/applesync.log 2>&1 +``` + +A lock file in `state_dir` prevents overlapping runs. + +## Notes + +- Apple Music and Qobuz access here uses unofficial endpoints. The Apple web + token is scraped (same approach as AQTransfer); the Qobuz app id is public. +- The Apple playlist is fetched through the catalog API in pages of 100; album + metadata is fetched in batches of 100 tracks, so playlists larger than that + work normally. +- `rip` is invoked once per run with a batch file of unique Qobuz album ids. diff --git a/applesync.example.toml b/applesync.example.toml new file mode 100644 index 0000000..adf4a24 --- /dev/null +++ b/applesync.example.toml @@ -0,0 +1,113 @@ +# AppleSync configuration example. +# +# AppleSync reads public Apple Music playlist URLs, finds each playlist track's +# album on Qobuz, downloads the full albums through the existing `rip` +# (streamrip-go) binary, and writes an m3u containing the playlist tracks. +# +# This example uses the paths on jirachi. Copy to applesync.toml and edit. + +[global] +# Where rip writes new downloads. AppleSync also passes this as `rip -f`. +downloads_dir = "/home/pihole/music/Full/QOBUZ_MONITOR" + +# Root of the final, imported music library that the music server scans. +# AppleSync looks for tracks here first (e.g. Full/Otta/ASTRA/06 STRANGER.flac) +# and falls back to downloads_dir for albums that have not been imported yet. +# Defaults to downloads_dir when omitted. +library_dir = "/home/pihole/music/Full" + +# Where generated m3u files are written. Relative entries in the m3u are +# resolved from each file's own directory. +m3u_dir = "/home/pihole/music/Full/Qobuz/Playlists" + +# "relative" (recommended) or "absolute" paths inside the m3u. +m3u_paths = "relative" + +# Default mode for every playlist: "replace" or "append". +# replace: rebuild the m3u to contain exactly the playlist tracks. +# append: keep existing entries, append only tracks not already listed. +mode = "replace" + +# Extended m3u: #EXTM3U plus #EXTINF lines. Set false for bare paths. +extended_m3u = true + +# What to do when a playlist track cannot be matched or found: +# warn: write the tracks that were found and report the rest (default) +# fail: do not write that playlist's m3u if anything is missing +missing = "warn" + +# Set true to make every run a dry run (useful while tuning). +dry_run = false + +# Concurrent Qobuz lookups (1-16). +concurrency = 4 + +# Match cache, run lock and rip batch files live here. +state_dir = "~/.local/state/applesync" + +# How to find downloaded files: +# albums only scan folders for the albums in the playlists (recommended for +# large libraries such as jirachi's Full tree) +# auto scan album folders, fall back to a full scan if many are missing +# all always scan the whole tree (slow) +library_scan = "albums" + +# Optional JSON report path. Can also be set with --report. +report = "" + +[apple] +# Apple's catalog language. The storefront is taken from the playlist URL. +language = "en-US" + +[qobuz] +# Public Qobuz app id. Leave empty to use the app id already present in rip's +# config, or to scrape the public one from play.qobuz.com. +app_id = "" + +[rip] +# rip is called as: +# rip [--no-progress] [--config-path ...] -q [-c ] +# -f file [--force] +# Use an absolute path for cron, where ~/.local/bin may not be in PATH. +binary = "/home/pihole/.local/bin/rip" + +# Optional path to a non-default rip config. AppleSync also reads this config +# for the Qobuz app id. +config_path = "" + +# Qobuz quality 0-4 (same scale as rip: 4 is the highest). +quality = 3 + +# Optional post-download conversion: ALAC, FLAC, OGG, MP3, AAC. +codec = "" + +# Extra global rip flags, e.g. ["--no-ssl-verify"]. +extra_args = [] + +# Pass --no-progress to rip (useful for cron logs). +no_progress = false + +[beets] +# Query the beets library for canonical paths and ISRCs. This is much faster +# than walking a large library and finds albums that have already been imported +# out of downloads_dir. Falls back to a filesystem scan if beets is unavailable +# or fails. +enabled = true +binary = "/home/pihole/.local/bin/beet" + +# Add one [[playlist]] block per playlist. + +[[playlist]] +url = "https://music.apple.com/us/playlist/indie-chill/pl.c4074df0f3114c7d9572859645229d75" + +# Optional display name. Defaults to the Apple playlist title. +# name = "indie + chill" + +# Optional m3u file name, relative to global.m3u_dir (or an absolute path). +# Defaults to slug(playlist name).m3u, e.g. indie-chill.m3u. +# m3u = "indie-chill.m3u" + +# Optional per-playlist mode override. +# mode = "append" + +enabled = true diff --git a/cmd/applesync/main.go b/cmd/applesync/main.go new file mode 100644 index 0000000..3916fd9 --- /dev/null +++ b/cmd/applesync/main.go @@ -0,0 +1,697 @@ +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 Config file (default: ./applesync.toml) + --playlist 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 Download at most n albums (testing aid) + --refresh-matches Ignore cached album matches for this run + --report 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 "" +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..4247458 --- /dev/null +++ b/go.mod @@ -0,0 +1,8 @@ +module applesync + +go 1.24 + +require ( + github.com/BurntSushi/toml v1.6.0 + github.com/dhowden/tag v0.0.0-20240417053706-3d75831295e8 +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..49432f7 --- /dev/null +++ b/go.sum @@ -0,0 +1,4 @@ +github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk= +github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho= +github.com/dhowden/tag v0.0.0-20240417053706-3d75831295e8 h1:OtSeLS5y0Uy01jaKK4mA/WVIYtpzVm63vLVAPzJXigg= +github.com/dhowden/tag v0.0.0-20240417053706-3d75831295e8/go.mod h1:apkPC/CR3s48O2D7Y++n1XWEpgPNNCjXYga3PPbJe2E= diff --git a/internal/apple/client.go b/internal/apple/client.go new file mode 100644 index 0000000..2cbe53f --- /dev/null +++ b/internal/apple/client.go @@ -0,0 +1,343 @@ +// Package apple talks to the public Apple Music catalog API. It scrapes a web +// player token (no Apple ID/login) and fetches playlists plus album metadata. +package apple + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "strconv" + "strings" + "sync" + "time" + + "applesync/internal/model" +) + +const defaultAPIBase = "https://amp-api.music.apple.com" + +type Client struct { + http *http.Client + language string + apiBase string + + mu sync.Mutex + token string + + logf func(string, ...any) +} + +func NewClient(language string) *Client { + if strings.TrimSpace(language) == "" { + language = "en-US" + } + return &Client{ + http: &http.Client{Timeout: 30 * time.Second}, + language: language, + apiBase: defaultAPIBase, + } +} + +func (c *Client) SetLogf(fn func(string, ...any)) { c.logf = fn } + +func (c *Client) log(format string, args ...any) { + if c.logf != nil { + c.logf(format, args...) + } +} + +func (c *Client) EnsureToken(ctx context.Context) error { + c.mu.Lock() + defer c.mu.Unlock() + if strings.TrimSpace(c.token) != "" { + return nil + } + token, err := FetchWebToken(ctx, c.http) + if err != nil { + return err + } + c.token = token + c.log("apple: web token acquired") + return nil +} + +func (c *Client) refreshToken(ctx context.Context) error { + token, err := FetchWebToken(ctx, c.http) + if err != nil { + return err + } + c.mu.Lock() + c.token = token + c.mu.Unlock() + c.log("apple: web token refreshed") + return nil +} + +func (c *Client) currentToken() string { + c.mu.Lock() + defer c.mu.Unlock() + return c.token +} + +// FetchPlaylist fetches a public playlist, following pagination. +func (c *Client) FetchPlaylist(ctx context.Context, ref PlaylistRef) (*model.Playlist, error) { + endpoint := fmt.Sprintf("%s/v1/catalog/%s/playlists/%s", c.apiBase, url.PathEscape(ref.Storefront), url.PathEscape(ref.PlaylistID)) + q := url.Values{} + q.Set("omit[resource]", "autos") + q.Set("include", "tracks") + q.Set("l", c.language) + + var first playlistResponse + if err := c.getJSON(ctx, endpoint+"?"+q.Encode(), &first); err != nil { + return nil, err + } + if len(first.Data) == 0 { + return nil, fmt.Errorf("apple playlist response missing data") + } + + item := first.Data[0] + pl := &model.Playlist{ + URL: ref.RawURL, + SourceID: item.ID, + Storefront: ref.Storefront, + Name: strings.TrimSpace(item.Attributes.Name), + } + for _, t := range item.Relationships.Tracks.Data { + pl.Tracks = append(pl.Tracks, toTrack(t)) + } + c.log("apple: playlist %q: %d tracks", pl.Name, len(pl.Tracks)) + + next := strings.TrimSpace(item.Relationships.Tracks.Next) + for next != "" { + nextURL := next + if strings.HasPrefix(nextURL, "/") { + nextURL = c.apiBase + nextURL + } + var page trackPage + if err := c.getJSON(ctx, nextURL, &page); err != nil { + return nil, err + } + for _, t := range page.Data { + pl.Tracks = append(pl.Tracks, toTrack(t)) + } + next = strings.TrimSpace(page.Next) + } + c.log("apple: playlist %q: fetched %d tracks", pl.Name, len(pl.Tracks)) + if len(pl.Tracks) == 0 { + return nil, fmt.Errorf("apple playlist %q has no tracks", pl.Name) + } + return pl, nil +} + +// EnrichAlbums batches the playlist tracks through the songs endpoint with +// include=albums. This is where album ids, UPCs, album artists and release +// dates come from; the playlist's own track list only carries album names. +func (c *Client) EnrichAlbums(ctx context.Context, pl *model.Playlist) error { + if len(pl.Tracks) == 0 { + return nil + } + byID := make(map[string]songItem, len(pl.Tracks)) + ids := make([]string, 0, len(pl.Tracks)) + for _, track := range pl.Tracks { + if track.AppleID != "" { + ids = append(ids, track.AppleID) + } + } + for start := 0; start < len(ids); start += 100 { + end := start + 100 + if end > len(ids) { + end = len(ids) + } + q := url.Values{} + q.Set("ids", strings.Join(ids[start:end], ",")) + q.Set("include", "albums") + q.Set("l", c.language) + endpoint := fmt.Sprintf("%s/v1/catalog/%s/songs?%s", c.apiBase, url.PathEscape(pl.Storefront), q.Encode()) + var resp songsResponse + if err := c.getJSON(ctx, endpoint, &resp); err != nil { + return err + } + for _, song := range resp.Data { + byID[song.ID] = song + } + } + + albumIndex := map[string]*model.Album{} + albumOrder := make([]*model.Album, 0, len(pl.Tracks)) + missingAlbums := 0 + for _, track := range pl.Tracks { + song, ok := byID[track.AppleID] + if ok { + mergeSong(track, song) + } + if track.AlbumID == "" { + missingAlbums++ + continue + } + album, seen := albumIndex[track.AlbumID] + if !seen { + artist := track.AlbumArtist + if artist == "" { + artist = track.ArtistName + } + album = &model.Album{ + AppleID: track.AlbumID, + Title: track.AlbumName, + Artist: artist, + UPC: track.AlbumUPC, + TrackCount: track.AlbumTrackCount, + ReleaseDate: track.AlbumReleaseDate, + } + if len(track.AlbumReleaseDate) >= 4 { + if year, err := strconv.Atoi(track.AlbumReleaseDate[:4]); err == nil { + album.Year = year + } + } + albumIndex[track.AlbumID] = album + albumOrder = append(albumOrder, album) + } + album.Tracks = append(album.Tracks, track) + } + pl.Albums = albumOrder + if missingAlbums > 0 { + c.log("apple: warning: %d playlist tracks have no album relationship", missingAlbums) + } + c.log("apple: playlist %q: %d unique albums", pl.Name, len(pl.Albums)) + return nil +} + +func toTrack(t playlistTrack) *model.Track { + at := t.Attributes + track := &model.Track{ + AppleID: strings.TrimSpace(t.ID), + Title: strings.TrimSpace(at.Name), + ArtistName: strings.TrimSpace(at.ArtistName), + AlbumName: strings.TrimSpace(at.AlbumName), + ISRC: strings.ToUpper(strings.TrimSpace(at.ISRC)), + DurationMS: at.DurationInMillis, + TrackNumber: at.TrackNumber, + DiscNumber: at.DiscNumber, + Explicit: strings.EqualFold(strings.TrimSpace(at.ContentRating), "explicit"), + } + if track.ArtistName != "" { + track.Artists = []string{track.ArtistName} + } + for _, album := range t.Relationships.Albums.Data { + if album.ID != "" { + track.AlbumID = album.ID + break + } + } + return track +} + +// mergeSong fills in fields that are only available from the songs endpoint. +func mergeSong(track *model.Track, song songItem) { + at := song.Attributes + if at.Name != "" { + track.Title = strings.TrimSpace(at.Name) + } + if at.ArtistName != "" { + track.ArtistName = strings.TrimSpace(at.ArtistName) + track.Artists = []string{track.ArtistName} + } + if at.AlbumName != "" { + track.AlbumName = strings.TrimSpace(at.AlbumName) + } + if at.ISRC != "" { + track.ISRC = strings.ToUpper(strings.TrimSpace(at.ISRC)) + } + if at.DurationInMillis > 0 { + track.DurationMS = at.DurationInMillis + } + if at.TrackNumber > 0 { + track.TrackNumber = at.TrackNumber + } + if at.DiscNumber > 0 { + track.DiscNumber = at.DiscNumber + } + track.Explicit = strings.EqualFold(strings.TrimSpace(at.ContentRating), "explicit") + + for _, album := range song.Relationships.Albums.Data { + if album.ID == "" { + continue + } + track.AlbumID = album.ID + aa := album.Attributes + if aa.Name != "" { + track.AlbumName = strings.TrimSpace(aa.Name) + } + if aa.ArtistName != "" { + track.AlbumArtist = strings.TrimSpace(aa.ArtistName) + } + track.AlbumUPC = strings.TrimSpace(aa.UPC) + track.AlbumTrackCount = aa.TrackCount + track.AlbumReleaseDate = strings.TrimSpace(aa.ReleaseDate) + break + } +} + +func (c *Client) getJSON(ctx context.Context, endpoint string, out any) error { + if err := c.EnsureToken(ctx); err != nil { + return err + } + allowRefresh := true + var lastErr error + for attempt := 1; attempt <= 4; attempt++ { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil) + if err != nil { + return err + } + req.Header.Set("Authorization", "Bearer "+c.currentToken()) + req.Header.Set("Origin", "https://music.apple.com") + req.Header.Set("User-Agent", browserUA) + + resp, err := c.http.Do(req) + if err != nil { + lastErr = err + sleep(ctx, time.Duration(attempt)*500*time.Millisecond) + continue + } + + if resp.StatusCode == http.StatusUnauthorized && allowRefresh { + _ = resp.Body.Close() + allowRefresh = false + if err := c.refreshToken(ctx); err != nil { + return fmt.Errorf("apple token refresh failed: %w", err) + } + continue + } + if resp.StatusCode == http.StatusTooManyRequests || resp.StatusCode >= 500 { + _ = resp.Body.Close() + lastErr = fmt.Errorf("apple api status %d", resp.StatusCode) + sleep(ctx, time.Duration(attempt)*time.Second) + continue + } + if resp.StatusCode >= 300 { + body, _ := io.ReadAll(io.LimitReader(resp.Body, 4096)) + _ = resp.Body.Close() + return fmt.Errorf("apple api error (%d): %s", resp.StatusCode, strings.TrimSpace(string(body))) + } + defer resp.Body.Close() + if err := json.NewDecoder(resp.Body).Decode(out); err != nil { + return err + } + return nil + } + if lastErr == nil { + lastErr = fmt.Errorf("apple request failed after retries") + } + return lastErr +} + +func sleep(ctx context.Context, d time.Duration) { + timer := time.NewTimer(d) + defer timer.Stop() + select { + case <-ctx.Done(): + case <-timer.C: + } +} diff --git a/internal/apple/client_test.go b/internal/apple/client_test.go new file mode 100644 index 0000000..b307513 --- /dev/null +++ b/internal/apple/client_test.go @@ -0,0 +1,55 @@ +package apple + +import ( + "context" + "net/http" + "net/http/httptest" + "testing" +) + +func TestFetchPlaylistAndEnrichAlbums(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/v1/catalog/us/playlists/pl.test": + _, _ = w.Write([]byte(`{"data":[{"id":"pl.test","attributes":{"name":"Test List"},"relationships":{"tracks":{"data":[{"id":"t1","attributes":{"name":"One","artistName":"Track Artist","albumName":"Album","isrc":"aaa","durationInMillis":100000}}],"next":"/next"}}}]}`)) + case "/next": + _, _ = w.Write([]byte(`{"data":[{"id":"t2","attributes":{"name":"Two","artistName":"Track Artist","albumName":"Album","isrc":"bbb","durationInMillis":120000}}],"next":""}`)) + case "/v1/catalog/us/songs": + if r.URL.Query().Get("include") != "albums" { + t.Errorf("include = %q", r.URL.Query().Get("include")) + } + _, _ = w.Write([]byte(`{"data":[{"id":"t1","attributes":{"name":"One","artistName":"Track Artist","albumName":"Album","isrc":"aaa","durationInMillis":100000,"trackNumber":1,"discNumber":1},"relationships":{"albums":{"data":[{"id":"al1","attributes":{"name":"Album - Single","artistName":"Album Artist","upc":"0617308063523","releaseDate":"2026-10-23","trackCount":2}}]}}},{"id":"t2","attributes":{"name":"Two","artistName":"Track Artist","albumName":"Album","isrc":"bbb","durationInMillis":120000,"trackNumber":2,"discNumber":1},"relationships":{"albums":{"data":[{"id":"al1","attributes":{"name":"Album - Single","artistName":"Album Artist","upc":"0617308063523","releaseDate":"2026-10-23","trackCount":2}}]}}}]}`)) + default: + http.NotFound(w, r) + } + })) + defer server.Close() + + client := NewClient("en-US") + client.apiBase = server.URL + client.http = server.Client() + client.token = "test-token" + + ref := PlaylistRef{Storefront: "us", PlaylistID: "pl.test", RawURL: "https://music.apple.com/us/playlist/test/pl.test"} + playlist, err := client.FetchPlaylist(context.Background(), ref) + if err != nil { + t.Fatal(err) + } + if playlist.Name != "Test List" || len(playlist.Tracks) != 2 { + t.Fatalf("unexpected playlist: %+v", playlist) + } + + if err := client.EnrichAlbums(context.Background(), playlist); err != nil { + t.Fatal(err) + } + if len(playlist.Albums) != 1 { + t.Fatalf("albums = %d", len(playlist.Albums)) + } + album := playlist.Albums[0] + if album.AppleID != "al1" || album.UPC != "0617308063523" || album.Artist != "Album Artist" || album.TrackCount != 2 || album.Year != 2026 { + t.Fatalf("unexpected album: %+v", album) + } + if len(album.Tracks) != 2 || album.Tracks[0].TrackNumber != 1 || album.Tracks[1].TrackNumber != 2 { + t.Fatalf("unexpected album tracks: %+v", album.Tracks) + } +} diff --git a/internal/apple/token.go b/internal/apple/token.go new file mode 100644 index 0000000..1eee303 --- /dev/null +++ b/internal/apple/token.go @@ -0,0 +1,125 @@ +package apple + +import ( + "context" + "encoding/base64" + "encoding/json" + "fmt" + "io" + "net/http" + "regexp" + "strings" +) + +const browserUA = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0 Safari/537.36" + +var ( + jsAssetRe = regexp.MustCompile(`/assets/index[^"']+\.js`) + jwtRe = regexp.MustCompile(`eyJ[A-Za-z0-9_\-]+\.[A-Za-z0-9_\-]+\.[A-Za-z0-9_\-]+`) +) + +// FetchWebToken scrapes a public Apple Music web-player token from the +// music.apple.com JavaScript bundle. The token is required for the catalog API +// but does not identify a user account. +func FetchWebToken(ctx context.Context, client *http.Client) (string, error) { + body, err := fetchText(ctx, client, "https://music.apple.com") + if err != nil { + return "", fmt.Errorf("apple token: %w", err) + } + assets := uniqueStrings(jsAssetRe.FindAllString(body, -1)) + if len(assets) == 0 { + return "", fmt.Errorf("apple token: no JavaScript asset found") + } + var best string + bestScore := -1 + for i, asset := range assets { + if i >= 8 { + break + } + assetURL := "https://music.apple.com" + asset + script, err := fetchText(ctx, client, assetURL) + if err != nil { + continue + } + for _, candidate := range uniqueStrings(jwtRe.FindAllString(script, -1)) { + score := tokenScore(candidate) + if score > bestScore { + bestScore = score + best = candidate + } + } + if bestScore >= 20 { + break + } + } + if best == "" || bestScore <= 0 { + return "", fmt.Errorf("apple token: no web token found in JavaScript bundle") + } + return best, nil +} + +func tokenScore(token string) int { + parts := strings.Split(token, ".") + if len(parts) != 3 { + return 0 + } + header := decodeJWTPart(parts[0]) + payload := decodeJWTPart(parts[1]) + score := 0 + if header["kid"] == "WebPlayKid" { + score += 10 + } + if payload["iss"] == "AMPWebPlay" { + score += 10 + } + return score +} + +func decodeJWTPart(part string) map[string]any { + data, err := base64.RawURLEncoding.DecodeString(part) + if err != nil { + // Some tokens may include padding. + data, err = base64.URLEncoding.DecodeString(part) + if err != nil { + return nil + } + } + var out map[string]any + if err := json.Unmarshal(data, &out); err != nil { + return nil + } + return out +} + +func fetchText(ctx context.Context, client *http.Client, rawURL string) (string, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil) + if err != nil { + return "", err + } + req.Header.Set("User-Agent", browserUA) + resp, err := client.Do(req) + if err != nil { + return "", err + } + defer resp.Body.Close() + if resp.StatusCode >= 300 { + return "", fmt.Errorf("%s: status %d", rawURL, resp.StatusCode) + } + data, err := io.ReadAll(io.LimitReader(resp.Body, 32<<20)) + if err != nil { + return "", err + } + return string(data), nil +} + +func uniqueStrings(values []string) []string { + seen := make(map[string]bool, len(values)) + out := make([]string, 0, len(values)) + for _, value := range values { + if !seen[value] { + seen[value] = true + out = append(out, value) + } + } + return out +} diff --git a/internal/apple/types.go b/internal/apple/types.go new file mode 100644 index 0000000..5d5c982 --- /dev/null +++ b/internal/apple/types.go @@ -0,0 +1,77 @@ +package apple + +// JSON shapes for the Apple Music catalog API. Only the fields applesync uses +// are modelled. + +type playlistResponse struct { + Data []struct { + ID string `json:"id"` + Attributes struct { + Name string `json:"name"` + } `json:"attributes"` + Relationships struct { + Tracks struct { + Data []playlistTrack `json:"data"` + Next string `json:"next"` + } `json:"tracks"` + } `json:"relationships"` + } `json:"data"` +} + +type trackPage struct { + Data []playlistTrack `json:"data"` + Next string `json:"next"` +} + +type playlistTrack struct { + ID string `json:"id"` + Attributes struct { + Name string `json:"name"` + ArtistName string `json:"artistName"` + AlbumName string `json:"albumName"` + ISRC string `json:"isrc"` + DurationInMillis int `json:"durationInMillis"` + TrackNumber int `json:"trackNumber"` + DiscNumber int `json:"discNumber"` + ContentRating string `json:"contentRating"` + } `json:"attributes"` + Relationships struct { + Albums struct { + Data []albumRel `json:"data"` + } `json:"albums"` + } `json:"relationships"` +} + +type songsResponse struct { + Data []songItem `json:"data"` +} + +type songItem struct { + ID string `json:"id"` + Attributes struct { + Name string `json:"name"` + ArtistName string `json:"artistName"` + AlbumName string `json:"albumName"` + ISRC string `json:"isrc"` + DurationInMillis int `json:"durationInMillis"` + TrackNumber int `json:"trackNumber"` + DiscNumber int `json:"discNumber"` + ContentRating string `json:"contentRating"` + } `json:"attributes"` + Relationships struct { + Albums struct { + Data []albumRel `json:"data"` + } `json:"albums"` + } `json:"relationships"` +} + +type albumRel struct { + ID string `json:"id"` + Attributes struct { + Name string `json:"name"` + ArtistName string `json:"artistName"` + UPC string `json:"upc"` + ReleaseDate string `json:"releaseDate"` + TrackCount int `json:"trackCount"` + } `json:"attributes"` +} diff --git a/internal/apple/url.go b/internal/apple/url.go new file mode 100644 index 0000000..29733a1 --- /dev/null +++ b/internal/apple/url.go @@ -0,0 +1,77 @@ +package apple + +import ( + "fmt" + "net/url" + "strings" +) + +// PlaylistRef is a parsed public Apple Music playlist URL. +type PlaylistRef struct { + Storefront string + PlaylistID string + RawURL string +} + +// ParsePlaylistURL validates a public music.apple.com playlist link. +func ParsePlaylistURL(raw string) (PlaylistRef, error) { + raw = strings.TrimSpace(raw) + u, err := url.Parse(raw) + if err != nil { + return PlaylistRef{}, fmt.Errorf("invalid Apple Music URL: %w", err) + } + if u.Scheme != "https" && u.Scheme != "http" { + return PlaylistRef{}, fmt.Errorf("Apple Music URL must use https") + } + host := strings.ToLower(u.Hostname()) + switch host { + case "music.apple.com", "beta.music.apple.com", "classical.music.apple.com": + default: + return PlaylistRef{}, fmt.Errorf("not an Apple Music URL: host %q", host) + } + + segments := splitPath(u.Path) + for _, segment := range segments { + if strings.EqualFold(segment, "library") { + return PlaylistRef{}, fmt.Errorf("library (private) playlists are not supported; use a public catalog playlist") + } + } + + ref := PlaylistRef{RawURL: raw, Storefront: "us"} + if len(segments) > 0 && isStorefront(segments[0]) { + ref.Storefront = strings.ToLower(segments[0]) + } + for _, segment := range segments { + if strings.HasPrefix(segment, "pl.") && len(segment) > 3 { + ref.PlaylistID = segment + break + } + } + if ref.PlaylistID == "" { + return PlaylistRef{}, fmt.Errorf("Apple Music URL does not contain a playlist id (pl.…)") + } + return ref, nil +} + +func splitPath(path string) []string { + parts := strings.Split(path, "/") + out := make([]string, 0, len(parts)) + for _, p := range parts { + if p != "" { + out = append(out, p) + } + } + return out +} + +func isStorefront(s string) bool { + if len(s) != 2 { + return false + } + for _, r := range strings.ToLower(s) { + if r < 'a' || r > 'z' { + return false + } + } + return true +} diff --git a/internal/apple/url_test.go b/internal/apple/url_test.go new file mode 100644 index 0000000..4a3e319 --- /dev/null +++ b/internal/apple/url_test.go @@ -0,0 +1,64 @@ +package apple + +import "testing" + +func TestParsePlaylistURL(t *testing.T) { + cases := []struct { + name string + url string + storefront string + playlist string + wantErr bool + }{ + { + name: "us playlist", + url: "https://music.apple.com/us/playlist/indie-chill/pl.c4074df0f3114c7d9572859645229d75", + storefront: "us", + playlist: "pl.c4074df0f3114c7d9572859645229d75", + }, + { + name: "gb playlist with query", + url: "https://music.apple.com/gb/playlist/name/pl.abc123?uo=4", + storefront: "gb", + playlist: "pl.abc123", + }, + { + name: "beta host", + url: "https://beta.music.apple.com/de/playlist/x/pl.123", + storefront: "de", + playlist: "pl.123", + }, + { + name: "wrong host", + url: "https://open.spotify.com/playlist/abc", + wantErr: true, + }, + { + name: "library playlist", + url: "https://music.apple.com/us/library/playlist/pl.123", + wantErr: true, + }, + { + name: "no playlist id", + url: "https://music.apple.com/us/album/name/123", + wantErr: true, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + ref, err := ParsePlaylistURL(tc.url) + if tc.wantErr { + if err == nil { + t.Fatalf("expected error, got %+v", ref) + } + return + } + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if ref.Storefront != tc.storefront || ref.PlaylistID != tc.playlist { + t.Fatalf("got %+v, want storefront=%s playlist=%s", ref, tc.storefront, tc.playlist) + } + }) + } +} diff --git a/internal/beets/beets.go b/internal/beets/beets.go new file mode 100644 index 0000000..b993d71 --- /dev/null +++ b/internal/beets/beets.go @@ -0,0 +1,182 @@ +// 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] + "…" +} diff --git a/internal/beets/beets_test.go b/internal/beets/beets_test.go new file mode 100644 index 0000000..0930183 --- /dev/null +++ b/internal/beets/beets_test.go @@ -0,0 +1,62 @@ +package beets + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" +) + +func TestFilesMergesQueriesByPath(t *testing.T) { + dir := t.TempDir() + script := filepath.Join(dir, "fake-beet") + content := `#!/bin/sh +printf '%s\n' "$@" >> "$0.args" +printf '/music/Artist/Album/01 Title.flac\tTitle\tArtist\tAlbum\tArtist\tABC123\n' +` + if err := os.WriteFile(script, []byte(content), 0o755); err != nil { + t.Fatal(err) + } + + runner := New(script) + files, err := runner.Files(context.Background(), []string{"ABC123"}, []string{"Album (Deluxe)"}) + if err != nil { + t.Fatal(err) + } + if len(files) != 1 { + t.Fatalf("files = %d, want 1 after merge", len(files)) + } + file := files[0] + if file.Path != "/music/Artist/Album/01 Title.flac" || file.Title != "Title" || file.Artist != "Artist" || file.Album != "Album" || file.ISRC != "ABC123" { + t.Fatalf("unexpected file: %+v", file) + } + + args, err := os.ReadFile(script + ".args") + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(args), "isrc::^(ABC123)$") { + t.Fatalf("isrc query missing:\n%s", args) + } + if !strings.Contains(string(args), `album::^(Album \(Deluxe\))$`) { + t.Fatalf("album query missing/unescaped:\n%s", args) + } +} + +func TestParseSkipsMalformedLines(t *testing.T) { + files, err := parse("bad line\n/music/a.flac\tT\tA\tAL\tAA\tisrc1\r\n") + if err != nil { + t.Fatal(err) + } + if len(files) != 1 || files[0].ISRC != "ISRC1" { + t.Fatalf("files = %+v", files) + } +} + +func TestUniqueValues(t *testing.T) { + got := uniqueValues([]string{"a", " a ", "b", ""}) + if len(got) != 2 || got[0] != "a" || got[1] != "b" { + t.Fatalf("uniqueValues = %#v", got) + } +} diff --git a/internal/config/config.go b/internal/config/config.go new file mode 100644 index 0000000..51c8809 --- /dev/null +++ b/internal/config/config.go @@ -0,0 +1,219 @@ +// Package config loads and validates the applesync TOML configuration. +package config + +import ( + "fmt" + "os" + "path/filepath" + "strings" + + "github.com/BurntSushi/toml" + + "applesync/internal/state" +) + +type Config struct { + Global GlobalConfig `toml:"global"` + Apple AppleConfig `toml:"apple"` + Qobuz QobuzConfig `toml:"qobuz"` + Rip RipConfig `toml:"rip"` + Beets BeetsConfig `toml:"beets"` + Playlists []PlaylistConfig `toml:"playlist"` +} + +type GlobalConfig struct { + DownloadsDir string `toml:"downloads_dir"` + LibraryDir string `toml:"library_dir"` + M3UDir string `toml:"m3u_dir"` + M3UPaths string `toml:"m3u_paths"` // relative | absolute + Mode string `toml:"mode"` // replace | append + ExtendedM3U bool `toml:"extended_m3u"` + Missing string `toml:"missing"` // warn | fail + DryRun bool `toml:"dry_run"` + Concurrency int `toml:"concurrency"` + StateDir string `toml:"state_dir"` + LibraryScan string `toml:"library_scan"` // auto | albums | all + Report string `toml:"report"` +} + +type AppleConfig struct { + Language string `toml:"language"` +} + +type QobuzConfig struct { + AppID string `toml:"app_id"` +} + +type RipConfig struct { + Binary string `toml:"binary"` + ConfigPath string `toml:"config_path"` + Quality int `toml:"quality"` + Codec string `toml:"codec"` + ExtraArgs []string `toml:"extra_args"` + NoProgress bool `toml:"no_progress"` +} + +type BeetsConfig struct { + Enabled bool `toml:"enabled"` + Binary string `toml:"binary"` +} + +type PlaylistConfig struct { + URL string `toml:"url"` + Name string `toml:"name"` + M3U string `toml:"m3u"` + Mode string `toml:"mode"` + Enabled *bool `toml:"enabled"` +} + +func (p PlaylistConfig) IsEnabled() bool { + return p.Enabled == nil || *p.Enabled +} + +func defaults() Config { + return Config{ + Global: GlobalConfig{ + M3UPaths: "relative", + Mode: "replace", + ExtendedM3U: true, + Missing: "warn", + Concurrency: 4, + StateDir: "~/.local/state/applesync", + LibraryScan: "auto", + }, + Apple: AppleConfig{Language: "en-US"}, + Rip: RipConfig{ + Binary: "rip", + Quality: 3, + }, + Beets: BeetsConfig{Binary: "beet"}, + } +} + +// FindPath resolves the config path: an explicit --config wins, otherwise +// ./applesync.toml and ~/.config/applesync/config.toml are tried. +func FindPath(explicit string) (string, error) { + if strings.TrimSpace(explicit) != "" { + path := state.ExpandPath(strings.TrimSpace(explicit)) + if _, err := os.Stat(path); err != nil { + return "", fmt.Errorf("config %s: %w", path, err) + } + return path, nil + } + candidates := []string{"applesync.toml", "~/.config/applesync/config.toml"} + for _, candidate := range candidates { + path := state.ExpandPath(candidate) + if info, err := os.Stat(path); err == nil && !info.IsDir() { + return path, nil + } + } + return "", fmt.Errorf("no config found; pass --config or create applesync.toml") +} + +// Load reads and validates a TOML config. +func Load(path string) (*Config, error) { + cfg := defaults() + if _, err := toml.DecodeFile(path, &cfg); err != nil { + return nil, fmt.Errorf("load %s: %w", path, err) + } + cfg.Global.DownloadsDir = state.ExpandPath(strings.TrimSpace(cfg.Global.DownloadsDir)) + cfg.Global.LibraryDir = state.ExpandPath(strings.TrimSpace(cfg.Global.LibraryDir)) + if cfg.Global.LibraryDir == "" { + cfg.Global.LibraryDir = cfg.Global.DownloadsDir + } + cfg.Global.M3UDir = state.ExpandPath(strings.TrimSpace(cfg.Global.M3UDir)) + cfg.Global.StateDir = state.ExpandPath(strings.TrimSpace(cfg.Global.StateDir)) + cfg.Global.Report = state.ExpandPath(strings.TrimSpace(cfg.Global.Report)) + cfg.Rip.ConfigPath = state.ExpandPath(strings.TrimSpace(cfg.Rip.ConfigPath)) + cfg.Beets.Binary = strings.TrimSpace(cfg.Beets.Binary) + + if err := cfg.Validate(); err != nil { + return nil, err + } + return &cfg, nil +} + +// Validate checks field values and cross-field rules. +func (c *Config) Validate() error { + g := &c.Global + if g.DownloadsDir == "" { + return fmt.Errorf("global.downloads_dir is required") + } + if g.M3UDir == "" { + return fmt.Errorf("global.m3u_dir is required") + } + g.Mode = strings.ToLower(strings.TrimSpace(g.Mode)) + if g.Mode != "replace" && g.Mode != "append" { + return fmt.Errorf("global.mode must be replace or append, got %q", g.Mode) + } + g.M3UPaths = strings.ToLower(strings.TrimSpace(g.M3UPaths)) + if g.M3UPaths != "relative" && g.M3UPaths != "absolute" { + return fmt.Errorf("global.m3u_paths must be relative or absolute, got %q", g.M3UPaths) + } + g.Missing = strings.ToLower(strings.TrimSpace(g.Missing)) + if g.Missing != "warn" && g.Missing != "fail" { + return fmt.Errorf("global.missing must be warn or fail, got %q", g.Missing) + } + g.LibraryScan = strings.ToLower(strings.TrimSpace(g.LibraryScan)) + if g.LibraryScan == "" { + g.LibraryScan = "auto" + } + if g.LibraryScan != "auto" && g.LibraryScan != "albums" && g.LibraryScan != "all" { + return fmt.Errorf("global.library_scan must be auto, albums or all, got %q", g.LibraryScan) + } + if g.Concurrency < 1 || g.Concurrency > 16 { + return fmt.Errorf("global.concurrency must be between 1 and 16, got %d", g.Concurrency) + } + if strings.TrimSpace(g.StateDir) == "" { + g.StateDir = "~/.local/state/applesync" + } + if len(c.Playlists) == 0 { + return fmt.Errorf("at least one [[playlist]] is required") + } + if strings.TrimSpace(c.Apple.Language) == "" { + c.Apple.Language = "en-US" + } + if strings.TrimSpace(c.Rip.Binary) == "" { + c.Rip.Binary = "rip" + } + if strings.TrimSpace(c.Beets.Binary) == "" { + c.Beets.Binary = "beet" + } + if c.Rip.Quality < 0 || c.Rip.Quality > 4 { + return fmt.Errorf("rip.quality must be between 0 and 4, got %d", c.Rip.Quality) + } + + enabled := 0 + explicitM3U := map[string]int{} + for i := range c.Playlists { + p := &c.Playlists[i] + p.URL = strings.TrimSpace(p.URL) + p.Name = strings.TrimSpace(p.Name) + p.M3U = strings.TrimSpace(p.M3U) + p.Mode = strings.ToLower(strings.TrimSpace(p.Mode)) + if p.Mode == "" { + p.Mode = g.Mode + } + if p.Mode != "replace" && p.Mode != "append" { + return fmt.Errorf("playlist %d: mode must be replace or append, got %q", i+1, p.Mode) + } + if !p.IsEnabled() { + continue + } + enabled++ + if p.URL == "" { + return fmt.Errorf("playlist %d: url is required", i+1) + } + if p.M3U != "" { + key := filepath.Clean(p.M3U) + explicitM3U[key]++ + if explicitM3U[key] > 1 { + return fmt.Errorf("playlist %d: m3u %q is used by more than one playlist", i+1, p.M3U) + } + } + } + if enabled == 0 { + return fmt.Errorf("no enabled [[playlist]] entries") + } + return nil +} diff --git a/internal/config/config_test.go b/internal/config/config_test.go new file mode 100644 index 0000000..ea0c412 --- /dev/null +++ b/internal/config/config_test.go @@ -0,0 +1,82 @@ +package config + +import ( + "os" + "path/filepath" + "testing" +) + +func writeConfig(t *testing.T, content string) string { + t.Helper() + path := filepath.Join(t.TempDir(), "applesync.toml") + if err := os.WriteFile(path, []byte(content), 0o644); err != nil { + t.Fatal(err) + } + return path +} + +func TestLoadDefaults(t *testing.T) { + path := writeConfig(t, ` +[global] +downloads_dir = "/music" +m3u_dir = "/playlists" + +[[playlist]] +url = "https://music.apple.com/us/playlist/x/pl.abc" +`) + cfg, err := Load(path) + if err != nil { + t.Fatal(err) + } + if cfg.Global.Mode != "replace" || cfg.Global.M3UPaths != "relative" || !cfg.Global.ExtendedM3U { + t.Fatalf("unexpected defaults: %+v", cfg.Global) + } + if cfg.Global.Concurrency != 4 || cfg.Rip.Quality != 3 { + t.Fatalf("unexpected defaults: %+v %+v", cfg.Global, cfg.Rip) + } + if cfg.Playlists[0].Mode != "replace" { + t.Fatalf("playlist mode = %q", cfg.Playlists[0].Mode) + } +} + +func TestExampleConfigLoads(t *testing.T) { + cfg, err := Load("../../applesync.example.toml") + if err != nil { + t.Fatal(err) + } + if len(cfg.Playlists) != 1 { + t.Fatalf("playlists = %d", len(cfg.Playlists)) + } +} + +func TestValidation(t *testing.T) { + cases := []string{ + ` +[global] +m3u_dir = "/playlists" +[[playlist]] +url = "https://music.apple.com/us/playlist/x/pl.abc" +`, + ` +[global] +downloads_dir = "/music" +m3u_dir = "/playlists" +mode = "mirror" +[[playlist]] +url = "https://music.apple.com/us/playlist/x/pl.abc" +`, + ` +[global] +downloads_dir = "/music" +m3u_dir = "/playlists" +[[playlist]] +url = "" +`, + } + for _, content := range cases { + path := writeConfig(t, content) + if _, err := Load(path); err == nil { + t.Fatalf("expected validation error for:\n%s", content) + } + } +} diff --git a/internal/library/library.go b/internal/library/library.go new file mode 100644 index 0000000..1bf4b99 --- /dev/null +++ b/internal/library/library.go @@ -0,0 +1,595 @@ +// 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 +} diff --git a/internal/library/library_test.go b/internal/library/library_test.go new file mode 100644 index 0000000..acfe42a --- /dev/null +++ b/internal/library/library_test.go @@ -0,0 +1,205 @@ +package library + +import ( + "context" + "os" + "path/filepath" + "testing" + + "applesync/internal/model" +) + +func TestReadTagsFilenameFallback(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "03. Some Artist - Some Title.flac") + if err := os.WriteFile(path, nil, 0o644); err != nil { + t.Fatal(err) + } + file, err := readTags(path) + if err != nil { + t.Fatal(err) + } + if file.Artist != "Some Artist" || file.Title != "Some Title" || file.TrackNumber != 3 { + t.Fatalf("unexpected file: %+v", file) + } +} + +func TestFindAlbumDirs(t *testing.T) { + album := &model.Album{AppleID: "a1", Title: "Popfly", Artist: "Michael Nau"} + match := &model.AlbumMatch{QobuzTitle: "Popfly", QobuzArtist: "Michael Nau"} + dirs := []dirInfo{ + {path: "/music/Michael Nau - Popfly (2026) [FLAC] [24B-44.1kHz]", norm: "michael nau popfly 2026 flac 24b 44 1khz"}, + {path: "/music/Other - Album", norm: "other album"}, + } + got := findAlbumDirs(album, match, dirs) + if len(got) != 1 || got[0] != dirs[0].path { + t.Fatalf("got %#v", got) + } +} + +func TestFindAlbumDirsLongTitlePrefix(t *testing.T) { + album := &model.Album{AppleID: "a1", Title: "A very long album title that will certainly exceed the truncation limit used by the ripper for folder names", Artist: "Artist"} + dirs := []dirInfo{ + {path: "/music/Artist - A very long album title that will certainly exceed the truncatio", norm: "artist a very long album title that will certainly exceed the truncatio"}, + } + got := findAlbumDirs(album, nil, dirs) + if len(got) != 1 { + t.Fatalf("got %#v", got) + } +} + +func newIndex(files ...*model.FileEntry) *Index { + 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{}, + } + for _, file := range files { + idx.add(file) + } + return idx +} + +func TestResolveByISRC(t *testing.T) { + file := &model.FileEntry{Path: "/music/a.flac", ISRC: "ABC123", Title: "One", Artist: "A", Album: "Album"} + idx := newIndex(file) + got, ok := idx.Resolve(&model.Track{Title: "Wrong", ArtistName: "B", ISRC: "ABC123"}, &model.Album{Title: "Album", Artist: "A"}, nil) + if !ok || got.Path != file.Path { + t.Fatalf("got %+v ok=%v", got, ok) + } +} + +func TestResolveByArtistTitle(t *testing.T) { + file := &model.FileEntry{Path: "/music/a.flac", Title: "One", Artist: "A", Album: "Album"} + idx := newIndex(file) + got, ok := idx.Resolve(&model.Track{Title: "One", ArtistName: "A"}, &model.Album{Title: "Album", Artist: "A"}, nil) + if !ok || got.Path != file.Path { + t.Fatalf("got %+v ok=%v", got, ok) + } +} + +func TestResolveRejectsWrongArtistSameTitle(t *testing.T) { + file := &model.FileEntry{Path: "/music/sinking.flac", Title: "Sinking", Artist: "Beatrice M.", Album: "Sinking"} + idx := newIndex(file) + got, ok := idx.Resolve( + &model.Track{Title: "Sinking", ArtistName: "Big Jesus Trash Can", AlbumName: "Sinking - Single"}, + &model.Album{Title: "Sinking - Single", Artist: "Big Jesus Trash Can"}, + nil, + ) + if ok { + t.Fatalf("expected no match, got %+v", got) + } +} + +func TestResolvePrefersImportedLibraryCopy(t *testing.T) { + root := t.TempDir() + downloads := filepath.Join(root, "staging") + library := filepath.Join(root, "library") + stagedDir := filepath.Join(downloads, "Michael Nau - Popfly (2026) [FLAC]") + importedDir := filepath.Join(library, "Michael Nau", "Popfly") + if err := os.MkdirAll(stagedDir, 0o755); err != nil { + t.Fatal(err) + } + if err := os.MkdirAll(importedDir, 0o755); err != nil { + t.Fatal(err) + } + staged := filepath.Join(stagedDir, "01. Michael Nau - Lost Station Hideaway.flac") + imported := filepath.Join(importedDir, "01. Michael Nau - Lost Station Hideaway.flac") + if err := os.WriteFile(staged, nil, 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(imported, nil, 0o644); err != nil { + t.Fatal(err) + } + albums := []*model.Album{{AppleID: "a1", Title: "Popfly", Artist: "Michael Nau", TrackCount: 10}} + matches := map[string]*model.AlbumMatch{"a1": {QobuzTitle: "Popfly", QobuzArtist: "Michael Nau"}} + idx, err := Build(context.Background(), downloads, library, albums, matches, "albums", nil) + if err != nil { + t.Fatal(err) + } + track := &model.Track{Title: "Lost Station Hideaway", ArtistName: "Michael Nau", AlbumName: "Popfly"} + got, ok := idx.Resolve(track, albums[0], matches["a1"]) + if !ok { + t.Fatal("no match") + } + if got.Path != imported { + t.Fatalf("resolved %s, want imported copy %s", got.Path, imported) + } +} + +func TestScanRootsNested(t *testing.T) { + roots := scanRoots("/music", "/music/staging") + if len(roots) != 1 || roots[0] != "/music" { + t.Fatalf("roots = %#v", roots) + } + roots = scanRoots("/library", "/staging") + if len(roots) != 2 { + t.Fatalf("roots = %#v", roots) + } +} + +func TestBuildWithBeetsPrefersLibrary(t *testing.T) { + root := t.TempDir() + downloads := filepath.Join(root, "staging") + libraryRoot := filepath.Join(root, "library") + stagedDir := filepath.Join(downloads, "Michael Nau - Popfly (2026) [FLAC]") + if err := os.MkdirAll(stagedDir, 0o755); err != nil { + t.Fatal(err) + } + if err := os.MkdirAll(filepath.Join(libraryRoot, "Michael Nau", "Popfly"), 0o755); err != nil { + t.Fatal(err) + } + staged := filepath.Join(stagedDir, "01. Michael Nau - Lost Station Hideaway.flac") + if err := os.WriteFile(staged, nil, 0o644); err != nil { + t.Fatal(err) + } + imported := filepath.Join(libraryRoot, "Michael Nau", "Popfly", "01 Lost Station Hideaway.flac") + beetsFiles := []*model.FileEntry{{ + Path: imported, Title: "Lost Station Hideaway", Artist: "Michael Nau", Album: "Popfly", ISRC: "ABC123", + }} + albums := []*model.Album{{AppleID: "a1", Title: "Popfly", Artist: "Michael Nau", TrackCount: 10}} + matches := map[string]*model.AlbumMatch{"a1": {QobuzTitle: "Popfly", QobuzArtist: "Michael Nau"}} + idx, err := BuildWithBeets(context.Background(), downloads, libraryRoot, beetsFiles, albums, matches, "albums", nil) + if err != nil { + t.Fatal(err) + } + + // ISRC match resolves to the beets library copy. + track := &model.Track{Title: "Lost Station Hideaway", ArtistName: "Michael Nau", AlbumName: "Popfly", ISRC: "ABC123"} + got, ok := idx.Resolve(track, albums[0], matches["a1"]) + if !ok || got.Path != imported { + t.Fatalf("got %+v ok=%v, want %s", got, ok, imported) + } + + // Artist/title match also prefers the library copy. + track.ISRC = "" + got, ok = idx.Resolve(track, albums[0], matches["a1"]) + if !ok || got.Path != imported { + t.Fatalf("got %+v ok=%v, want %s", got, ok, imported) + } +} + +func TestBuildAndResolve(t *testing.T) { + root := t.TempDir() + albumDir := filepath.Join(root, "Michael Nau - Popfly (2026) [FLAC] [24B-44.1kHz]") + if err := os.MkdirAll(albumDir, 0o755); err != nil { + t.Fatal(err) + } + file := filepath.Join(albumDir, "01. Michael Nau - Lost Station Hideaway.flac") + if err := os.WriteFile(file, nil, 0o644); err != nil { + t.Fatal(err) + } + albums := []*model.Album{{AppleID: "a1", Title: "Popfly", Artist: "Michael Nau", TrackCount: 10}} + matches := map[string]*model.AlbumMatch{"a1": {QobuzTitle: "Popfly", QobuzArtist: "Michael Nau"}} + idx, err := Build(context.Background(), root, root, albums, matches, "albums", nil) + if err != nil { + t.Fatal(err) + } + track := &model.Track{Title: "Lost Station Hideaway", ArtistName: "Michael Nau", AlbumName: "Popfly"} + got, ok := idx.Resolve(track, albums[0], matches["a1"]) + if !ok || filepath.Base(got.Path) != filepath.Base(file) { + t.Fatalf("got %+v ok=%v", got, ok) + } +} diff --git a/internal/m3u/m3u.go b/internal/m3u/m3u.go new file mode 100644 index 0000000..e747bc2 --- /dev/null +++ b/internal/m3u/m3u.go @@ -0,0 +1,165 @@ +// Package m3u writes extended m3u playlists in replace or append mode. +package m3u + +import ( + "fmt" + "os" + "path/filepath" + "strings" + + "applesync/internal/model" + "applesync/internal/state" +) + +// Entry is one playlist track mapped to a downloaded file. +type Entry struct { + File *model.FileEntry + Track *model.Track +} + +// Write writes entries to path. In replace mode the file is rebuilt; in append +// mode existing path lines are kept and only new files are appended. Paths are +// rendered relative to the m3u file or as absolute paths. +func Write(path string, entries []Entry, mode, pathStyle string, extended bool) (int, error) { + mode = strings.ToLower(strings.TrimSpace(mode)) + if mode == "" { + mode = "replace" + } + pathStyle = strings.ToLower(strings.TrimSpace(pathStyle)) + if pathStyle == "" { + pathStyle = "relative" + } + + switch mode { + case "replace": + var b strings.Builder + b.WriteString("#EXTM3U\n") + written := 0 + for _, entry := range entries { + line, err := renderPath(path, entry.File.Path, pathStyle) + if err != nil { + return 0, err + } + if extended { + b.WriteString(extinf(entry.Track)) + } + b.WriteString(line) + b.WriteString("\n") + written++ + } + if err := state.WriteFileAtomic(path, []byte(b.String())); err != nil { + return 0, err + } + _ = os.Chmod(path, 0o644) + return written, nil + + case "append": + existing, err := os.ReadFile(path) + if err != nil && !os.IsNotExist(err) { + return 0, err + } + existingSet := existingPaths(string(existing), filepath.Dir(path)) + var b strings.Builder + b.Write(existing) + if len(existing) > 0 && !strings.HasSuffix(string(existing), "\n") { + b.WriteString("\n") + } + if len(existing) == 0 { + b.WriteString("#EXTM3U\n") + } + written := 0 + for _, entry := range entries { + identity := identityPath(entry.File.Path, filepath.Dir(path)) + if existingSet[identity] { + continue + } + line, err := renderPath(path, entry.File.Path, pathStyle) + if err != nil { + return written, err + } + if extended { + b.WriteString(extinf(entry.Track)) + } + b.WriteString(line) + b.WriteString("\n") + existingSet[identity] = true + written++ + } + if written == 0 { + return 0, nil + } + if err := state.WriteFileAtomic(path, []byte(b.String())); err != nil { + return written, err + } + _ = os.Chmod(path, 0o644) + return written, nil + default: + return 0, fmt.Errorf("unknown m3u mode %q", mode) + } +} + +func extinf(track *model.Track) string { + if track == nil { + return "#EXTINF:-1,\n" + } + seconds := track.DurationMS / 1000 + if seconds < 0 { + seconds = 0 + } + label := strings.TrimSpace(track.ArtistName + " - " + track.Title) + if label == "" { + label = track.Title + } + return fmt.Sprintf("#EXTINF:%d,%s\n", seconds, sanitize(label)) +} + +func sanitize(value string) string { + value = strings.ReplaceAll(value, "\r", " ") + value = strings.ReplaceAll(value, "\n", " ") + return strings.TrimSpace(value) +} + +func renderPath(m3uPath, filePath, style string) (string, error) { + abs, err := filepath.Abs(filePath) + if err != nil { + return "", err + } + if style == "absolute" { + return filepath.ToSlash(abs), nil + } + dir, err := filepath.Abs(filepath.Dir(m3uPath)) + if err != nil { + return "", err + } + rel, err := filepath.Rel(dir, abs) + if err != nil { + return filepath.ToSlash(abs), nil + } + return filepath.ToSlash(rel), nil +} + +func identityPath(filePath, m3uDir string) string { + if strings.Contains(filePath, "://") { + return filePath + } + if !filepath.IsAbs(filePath) { + filePath = filepath.Join(m3uDir, filePath) + } + abs, err := filepath.Abs(filePath) + if err != nil { + return filepath.Clean(filePath) + } + return filepath.Clean(abs) +} + +func existingPaths(content, m3uDir string) map[string]bool { + out := map[string]bool{} + for _, line := range strings.Split(content, "\n") { + line = strings.TrimSpace(strings.TrimSuffix(line, "\r")) + if line == "" || strings.HasPrefix(line, "#") { + continue + } + out[identityPath(line, m3uDir)] = true + } + return out +} diff --git a/internal/m3u/m3u_test.go b/internal/m3u/m3u_test.go new file mode 100644 index 0000000..e03af46 --- /dev/null +++ b/internal/m3u/m3u_test.go @@ -0,0 +1,128 @@ +package m3u + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "applesync/internal/model" +) + +func entry(path, artist, title string, ms int) Entry { + return Entry{ + File: &model.FileEntry{Path: path}, + Track: &model.Track{ArtistName: artist, Title: title, DurationMS: ms}, + } +} + +func TestReplaceRelative(t *testing.T) { + root := t.TempDir() + music := filepath.Join(root, "music", "Album") + if err := os.MkdirAll(music, 0o755); err != nil { + t.Fatal(err) + } + file := filepath.Join(music, "01. Artist - One.flac") + if err := os.WriteFile(file, []byte("x"), 0o644); err != nil { + t.Fatal(err) + } + m3uPath := filepath.Join(root, "playlists", "list.m3u") + if _, err := Write(m3uPath, []Entry{entry(file, "Artist", "One", 215000)}, "replace", "relative", true); err != nil { + t.Fatal(err) + } + data, err := os.ReadFile(m3uPath) + if err != nil { + t.Fatal(err) + } + want := "#EXTM3U\n#EXTINF:215,Artist - One\n../music/Album/01. Artist - One.flac\n" + if string(data) != want { + t.Fatalf("got:\n%s\nwant:\n%s", data, want) + } + info, err := os.Stat(m3uPath) + if err != nil { + t.Fatal(err) + } + if info.Mode().Perm() != 0o644 { + t.Fatalf("mode = %v, want 0644", info.Mode().Perm()) + } +} + +func TestReplaceAbsolute(t *testing.T) { + root := t.TempDir() + file := filepath.Join(root, "a.flac") + if err := os.WriteFile(file, []byte("x"), 0o644); err != nil { + t.Fatal(err) + } + m3uPath := filepath.Join(root, "list.m3u") + if _, err := Write(m3uPath, []Entry{entry(file, "A", "B", 1000)}, "replace", "absolute", false); err != nil { + t.Fatal(err) + } + data, _ := os.ReadFile(m3uPath) + if !strings.Contains(string(data), "#EXTM3U\n") || !strings.Contains(string(data), file) { + t.Fatalf("unexpected m3u:\n%s", data) + } + if strings.Contains(string(data), "#EXTINF") { + t.Fatalf("plain m3u must not contain EXTINF:\n%s", data) + } +} + +func TestAppendDeduplicates(t *testing.T) { + root := t.TempDir() + one := filepath.Join(root, "one.flac") + two := filepath.Join(root, "two.flac") + _ = os.WriteFile(one, []byte("1"), 0o644) + _ = os.WriteFile(two, []byte("2"), 0o644) + m3uPath := filepath.Join(root, "list.m3u") + + if _, err := Write(m3uPath, []Entry{entry(one, "A", "One", 1000)}, "replace", "relative", true); err != nil { + t.Fatal(err) + } + written, err := Write(m3uPath, []Entry{ + entry(one, "A", "One", 1000), + entry(two, "B", "Two", 2000), + }, "append", "relative", true) + if err != nil { + t.Fatal(err) + } + if written != 1 { + t.Fatalf("written = %d, want 1", written) + } + data, _ := os.ReadFile(m3uPath) + if strings.Count(string(data), "one.flac") != 1 { + t.Fatalf("duplicate one.flac:\n%s", data) + } + if !strings.Contains(string(data), "two.flac") { + t.Fatalf("two.flac missing:\n%s", data) + } +} + +func TestAppendMissingFile(t *testing.T) { + root := t.TempDir() + file := filepath.Join(root, "one.flac") + _ = os.WriteFile(file, []byte("1"), 0o644) + m3uPath := filepath.Join(root, "new.m3u") + if _, err := Write(m3uPath, []Entry{entry(file, "A", "One", 1000)}, "append", "relative", true); err != nil { + t.Fatal(err) + } + data, _ := os.ReadFile(m3uPath) + if !strings.HasPrefix(string(data), "#EXTM3U\n") { + t.Fatalf("missing header:\n%s", data) + } +} + +func TestAppendDedupesExistingPlainPaths(t *testing.T) { + root := t.TempDir() + file := filepath.Join(root, "one.flac") + _ = os.WriteFile(file, []byte("1"), 0o644) + m3uPath := filepath.Join(root, "list.m3u") + if err := os.WriteFile(m3uPath, []byte("one.flac\r\n"), 0o644); err != nil { + t.Fatal(err) + } + written, err := Write(m3uPath, []Entry{entry(file, "A", "One", 1000)}, "append", "relative", true) + if err != nil { + t.Fatal(err) + } + if written != 0 { + t.Fatalf("written = %d, want 0", written) + } +} diff --git a/internal/matcher/matcher.go b/internal/matcher/matcher.go new file mode 100644 index 0000000..4c52f05 --- /dev/null +++ b/internal/matcher/matcher.go @@ -0,0 +1,442 @@ +// Package matcher matches Apple Music albums to Qobuz albums. It tries UPC +// first, then a fuzzy artist/title search, and verifies fuzzy candidates by +// comparing the ISRCs of the playlist tracks against the Qobuz track list. +package matcher + +import ( + "context" + "fmt" + "sort" + "strings" + "sync" + "sync/atomic" + "time" + + "applesync/internal/model" + "applesync/internal/state" + "applesync/internal/text" +) + +type QobuzClient interface { + SearchAlbums(ctx context.Context, query string, limit int) ([]model.QobuzAlbum, error) + GetAlbum(ctx context.Context, albumID string) (*model.QobuzAlbum, error) +} + +type Matcher struct { + client QobuzClient + cache *state.MatchCache + concurrency int + refresh bool + logf func(string, ...any) +} + +func New(client QobuzClient, cache *state.MatchCache, concurrency int) *Matcher { + if concurrency < 1 { + concurrency = 1 + } + return &Matcher{client: client, cache: cache, concurrency: concurrency} +} + +func (m *Matcher) SetLogf(fn func(string, ...any)) { m.logf = fn } + +// SetRefresh makes the matcher ignore existing cache entries (including +// negative ones) for this run. New results are still cached. +func (m *Matcher) SetRefresh(refresh bool) { m.refresh = refresh } + +func (m *Matcher) log(format string, args ...any) { + if m.logf != nil { + m.logf(format, args...) + } +} + +// MatchAll matches every album concurrently. Albums that cannot be matched are +// absent from the map; their reasons are cached and logged. +func (m *Matcher) MatchAll(ctx context.Context, albums []*model.Album) (map[string]*model.AlbumMatch, error) { + matches := make(map[string]*model.AlbumMatch, len(albums)) + var mu sync.Mutex + var done atomic.Int64 + total := len(albums) + + sem := make(chan struct{}, m.concurrency) + var wg sync.WaitGroup + for _, album := range albums { + wg.Add(1) + go func(album *model.Album) { + defer wg.Done() + select { + case sem <- struct{}{}: + defer func() { <-sem }() + case <-ctx.Done(): + return + } + match, err := m.matchOne(ctx, album) + n := done.Add(1) + if err != nil { + m.log("qobuz: [%d/%d] %s — %s: error: %v", n, total, album.Artist, album.Title, err) + return + } + if match != nil { + mu.Lock() + matches[album.AppleID] = match + mu.Unlock() + m.log("qobuz: [%d/%d] %s — %s -> %s [%s]", n, total, album.Artist, album.Title, match.QobuzAlbumID, match.Method) + return + } + m.log("qobuz: [%d/%d] %s — %s: no match", n, total, album.Artist, album.Title) + }(album) + } + wg.Wait() + if err := ctx.Err(); err != nil { + return matches, err + } + return matches, nil +} + +func (m *Matcher) matchOne(ctx context.Context, album *model.Album) (*model.AlbumMatch, error) { + if album.AppleID == "" { + return nil, fmt.Errorf("album has no Apple id") + } + if m.cache != nil && !m.refresh { + if entry, ok := m.cache.Get(album.AppleID); ok { + if entry.Match != nil { + match := *entry.Match + if match.AppleAlbumID == "" { + match.AppleAlbumID = album.AppleID + } + return &match, nil + } + if entry.Error != "" { + m.log("qobuz: cached miss for %s — %s: %s", album.Artist, album.Title, entry.Error) + return nil, nil + } + } + } + + match, reason, err := m.lookup(ctx, album) + now := time.Now() + if err != nil { + return nil, err + } + if match != nil { + match.AppleAlbumID = album.AppleID + match.CheckedAt = now + if m.cache != nil { + m.cache.Put(album.AppleID, model.CachedMatch{Match: match, CheckedAt: now}) + } + return match, nil + } + if m.cache != nil { + m.cache.Put(album.AppleID, model.CachedMatch{Error: reason, CheckedAt: now}) + } + return nil, nil +} + +func (m *Matcher) lookup(ctx context.Context, album *model.Album) (*model.AlbumMatch, string, error) { + upc := normalizeUPC(album.UPC) + if upc != "" { + for _, variant := range upcVariants(album.UPC) { + candidates, err := m.client.SearchAlbums(ctx, variant, 10) + if err != nil { + return nil, "", err + } + var exact []model.QobuzAlbum + for _, candidate := range candidates { + if normalizeUPC(candidate.UPC) == upc { + exact = append(exact, candidate) + } + } + if len(exact) > 0 { + sort.SliceStable(exact, func(i, j int) bool { + return score(album, exact[i]) > score(album, exact[j]) + }) + best := exact[0] + // Enrich the match when possible; a failure here does not + // invalidate an exact UPC match. + _ = verify(ctx, m.client, album, &best) + return toMatch(&best, "upc", 1.0), "", nil + } + } + } + + cleanTitle := text.SearchTitle(album.Title) + queries := uniqueQueries( + strings.TrimSpace(album.Artist+" "+cleanTitle), + strings.TrimSpace(cleanTitle+" "+album.Artist), + cleanTitle, + ) + seen := map[string]bool{} + var candidates []model.QobuzAlbum + for _, query := range queries { + if query == "" { + continue + } + found, err := m.client.SearchAlbums(ctx, query, 10) + if err != nil { + return nil, "", err + } + for _, candidate := range found { + if candidate.ID == "" || seen[candidate.ID] { + continue + } + seen[candidate.ID] = true + candidates = append(candidates, candidate) + } + } + type scored struct { + album model.QobuzAlbum + score float64 + } + ranked := make([]scored, 0, len(candidates)) + for _, candidate := range candidates { + s := score(album, candidate) + if text.Similarity(candidate.Title, cleanTitle) < 0.85 { + continue + } + if album.Artist != "" && text.Similarity(candidate.Artist, album.Artist) < 0.60 { + continue + } + ranked = append(ranked, scored{album: candidate, score: s}) + } + sort.SliceStable(ranked, func(i, j int) bool { return ranked[i].score > ranked[j].score }) + if len(ranked) == 0 || ranked[0].score < 0.72 { + return nil, "no Qobuz search match", nil + } + + maxVerify := 3 + for i := 0; i < len(ranked) && i < maxVerify; i++ { + candidate := ranked[i].album + full, err := m.client.GetAlbum(ctx, candidate.ID) + if err != nil { + continue + } + if full.TrackCount > 0 { + candidate.TrackCount = full.TrackCount + } + if full.Title != "" { + candidate.Title = full.Title + } + if full.Artist != "" { + candidate.Artist = full.Artist + } + method := verifyISRCs(album, full) + if method != "" { + conf := ranked[i].score + if method == "isrc" { + conf = maxFloat(conf, 0.95) + } + return toMatch(&candidate, method, conf), "", nil + } + // A very strong metadata match can be accepted even when Qobuz has no + // ISRC tags, as long as the track count also agrees. + if len(full.Tracks) > 0 && countISRCs(full) == 0 && ranked[i].score >= 0.92 && trackCountEqual(album, full) { + return toMatch(&candidate, "fuzzy", ranked[i].score), "", nil + } + } + return nil, "Qobuz candidates did not verify", nil +} + +func verify(ctx context.Context, client QobuzClient, album *model.Album, candidate *model.QobuzAlbum) error { + full, err := client.GetAlbum(ctx, candidate.ID) + if err != nil { + return err + } + if full.TrackCount > 0 { + candidate.TrackCount = full.TrackCount + } + if candidate.Title == "" { + candidate.Title = full.Title + } + if candidate.Artist == "" { + candidate.Artist = full.Artist + } + return nil +} + +// verifyISRCs returns "isrc" if enough of the playlist track ISRCs are present +// on the Qobuz album, "fuzzy" if the metadata is strong but ISRCs are missing, +// and "" if the candidate should be rejected. +func verifyISRCs(album *model.Album, qalbum *model.QobuzAlbum) string { + appleISRCs := make(map[string]bool) + for _, track := range album.Tracks { + if track.ISRC != "" { + appleISRCs[track.ISRC] = true + } + } + qISRCs := make(map[string]bool) + for _, track := range qalbum.Tracks { + if track.ISRC != "" { + qISRCs[track.ISRC] = true + } + } + overlap := 0 + for isrc := range appleISRCs { + if qISRCs[isrc] { + overlap++ + } + } + // Qobuz and Apple sometimes carry different editions of the same album: + // identical artist, title, year and track count but different UPCs and a + // shifted ISRC block. Treat that as a strong match rather than rejecting it. + strong := metadataStrong(album, qalbum) + if len(appleISRCs) == 0 { + if strong { + return "fuzzy" + } + return "" + } + if overlap == 0 { + if strong { + return "fuzzy" + } + return "" + } + if overlap == len(appleISRCs) { + return "isrc" + } + if overlap >= 1 { + // Even a partial ISRC overlap is strong evidence when the release + // metadata agrees; Qobuz may only carry a shorter edition than Apple. + // If the playlist uses more than one track from this album, the Qobuz + // edition must at least be large enough to contain them. + playlistTracks := len(album.Tracks) + if playlistTracks == 0 { + playlistTracks = len(appleISRCs) + } + if qalbum.TrackCount > 0 && qalbum.TrackCount < playlistTracks && overlap < len(appleISRCs) { + return "" + } + titleSim := text.Similarity(qalbum.Title, text.SearchTitle(album.Title)) + artistSim := text.Similarity(qalbum.Artist, album.Artist) + if titleSim >= 0.90 && artistSim >= 0.85 { + return "isrc" + } + } + return "" +} + +func metadataStrong(album *model.Album, qalbum *model.QobuzAlbum) bool { + if !trackCountEqual(album, qalbum) { + return false + } + titleSim := text.Similarity(qalbum.Title, text.SearchTitle(album.Title)) + artistSim := text.Similarity(qalbum.Artist, album.Artist) + if titleSim < 0.95 || artistSim < 0.85 { + return false + } + if album.Year > 0 && qalbum.Year > 0 { + diff := album.Year - qalbum.Year + if diff < 0 { + diff = -diff + } + if diff > 1 { + return false + } + } + return true +} + +func countISRCs(album *model.QobuzAlbum) int { + n := 0 + for _, track := range album.Tracks { + if track.ISRC != "" { + n++ + } + } + return n +} + +func trackCountEqual(a *model.Album, b *model.QobuzAlbum) bool { + return a.TrackCount > 0 && b.TrackCount > 0 && a.TrackCount == b.TrackCount +} + +func score(album *model.Album, candidate model.QobuzAlbum) float64 { + titleSim := text.Similarity(candidate.Title, text.SearchTitle(album.Title)) + artistSim := text.Similarity(candidate.Artist, album.Artist) + s := 0.55*titleSim + 0.30*artistSim + if album.TrackCount > 0 && candidate.TrackCount > 0 { + if album.TrackCount == candidate.TrackCount { + s += 0.10 + } else { + s -= 0.10 + } + } + if album.Year > 0 && candidate.Year > 0 { + diff := album.Year - candidate.Year + if diff < 0 { + diff = -diff + } + switch { + case diff <= 1: + s += 0.05 + case diff > 3: + s -= 0.05 + } + } + if text.IsNoisyAlbum(candidate.Title) { + s -= 0.15 + } + return s +} + +func toMatch(candidate *model.QobuzAlbum, method string, confidence float64) *model.AlbumMatch { + return &model.AlbumMatch{ + QobuzAlbumID: candidate.ID, + QobuzTitle: candidate.Title, + QobuzArtist: candidate.Artist, + QobuzUPC: candidate.UPC, + QobuzTrackCount: candidate.TrackCount, + Method: method, + Confidence: confidence, + } +} + +func normalizeUPC(value string) string { + var b strings.Builder + for _, r := range value { + if r >= '0' && r <= '9' { + b.WriteRune(r) + } + } + return strings.TrimLeft(b.String(), "0") +} + +func upcVariants(value string) []string { + digits := normalizeUPC(value) + if digits == "" { + return nil + } + variants := []string{digits} + if len(digits) < 13 { + variants = append([]string{strings.Repeat("0", 13-len(digits)) + digits}, variants...) + } + seen := map[string]bool{} + out := make([]string, 0, len(variants)) + for _, v := range variants { + if v != "" && !seen[v] { + seen[v] = true + out = append(out, v) + } + } + return out +} + +func uniqueQueries(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 maxFloat(a, b float64) float64 { + if a > b { + return a + } + return b +} diff --git a/internal/matcher/matcher_test.go b/internal/matcher/matcher_test.go new file mode 100644 index 0000000..841651e --- /dev/null +++ b/internal/matcher/matcher_test.go @@ -0,0 +1,173 @@ +package matcher + +import ( + "context" + "errors" + "testing" + + "applesync/internal/model" +) + +type fakeQobuz struct { + results []model.QobuzAlbum + albums map[string]model.QobuzAlbum +} + +func (f *fakeQobuz) SearchAlbums(context.Context, string, int) ([]model.QobuzAlbum, error) { + return f.results, nil +} + +func (f *fakeQobuz) GetAlbum(_ context.Context, id string) (*model.QobuzAlbum, error) { + album, ok := f.albums[id] + if !ok { + return nil, errors.New("not found") + } + return &album, nil +} + +func TestMatchUPC(t *testing.T) { + album := &model.Album{ + AppleID: "apple-1", + Title: "Popfly", + Artist: "Michael Nau", + UPC: "617308063523", + TrackCount: 10, + Year: 2026, + Tracks: []*model.Track{{ISRC: "US33X2624501"}}, + } + q := &fakeQobuz{ + results: []model.QobuzAlbum{{ID: "q1", Title: "Popfly", Artist: "Michael Nau", UPC: "0617308063523", TrackCount: 10, Year: 2026}}, + albums: map[string]model.QobuzAlbum{"q1": {ID: "q1", Title: "Popfly", Artist: "Michael Nau", TrackCount: 10}}, + } + m := New(q, nil, 1) + matches, err := m.MatchAll(context.Background(), []*model.Album{album}) + if err != nil { + t.Fatal(err) + } + match := matches["apple-1"] + if match == nil || match.QobuzAlbumID != "q1" || match.Method != "upc" { + t.Fatalf("unexpected match: %+v", match) + } +} + +func TestMatchFuzzyStrongMetadataWithDifferentISRCs(t *testing.T) { + album := &model.Album{ + AppleID: "apple-1", + Title: "Train on the Island", + Artist: "Aldous Harding", + UPC: "191400087378", + TrackCount: 10, + Year: 2026, + Tracks: []*model.Track{{ISRC: "GBAFL2500561"}}, + } + q := &fakeQobuz{ + results: []model.QobuzAlbum{{ID: "q1", Title: "Train on the Island", Artist: "Aldous Harding", UPC: "0191400087361", TrackCount: 10, Year: 2026}}, + albums: map[string]model.QobuzAlbum{"q1": { + ID: "q1", Title: "Train on the Island", Artist: "Aldous Harding", TrackCount: 10, Year: 2026, + Tracks: []model.QobuzTrack{{ISRC: "GBAFL2500549"}}, + }}, + } + m := New(q, nil, 1) + matches, err := m.MatchAll(context.Background(), []*model.Album{album}) + if err != nil { + t.Fatal(err) + } + match := matches["apple-1"] + if match == nil || match.Method != "fuzzy" { + t.Fatalf("unexpected match: %+v", match) + } +} + +func TestMatchShortEditionPartialISRC(t *testing.T) { + album := &model.Album{ + AppleID: "apple-1", + Title: "The X-panded Universe - Single", + Artist: "Father John Misty", + UPC: "098787965360", + TrackCount: 3, + Year: 2026, + Tracks: []*model.Track{{ISRC: "USSUB2572602"}}, + } + q := &fakeQobuz{ + results: []model.QobuzAlbum{{ID: "q1", Title: "The X-panded Universe", Artist: "Father John Misty", UPC: "0098787170566", TrackCount: 1, Year: 2026}}, + albums: map[string]model.QobuzAlbum{"q1": { + ID: "q1", Title: "The X-panded Universe", Artist: "Father John Misty", TrackCount: 1, Year: 2026, + Tracks: []model.QobuzTrack{{ISRC: "USSUB2572602"}}, + }}, + } + m := New(q, nil, 1) + matches, err := m.MatchAll(context.Background(), []*model.Album{album}) + if err != nil { + t.Fatal(err) + } + if match := matches["apple-1"]; match == nil || match.Method != "isrc" { + t.Fatalf("unexpected match: %+v", match) + } +} + +func TestMatchRejectsShortEditionForMultiTrackPlaylist(t *testing.T) { + album := &model.Album{ + AppleID: "apple-1", + Title: "Album", + Artist: "Artist", + UPC: "111", + TrackCount: 5, + Year: 2026, + Tracks: []*model.Track{ + {ISRC: "AAA"}, + {ISRC: "BBB"}, + }, + } + q := &fakeQobuz{ + results: []model.QobuzAlbum{{ID: "q1", Title: "Album", Artist: "Artist", UPC: "222", TrackCount: 1, Year: 2026}}, + albums: map[string]model.QobuzAlbum{"q1": { + ID: "q1", Title: "Album", Artist: "Artist", TrackCount: 1, Year: 2026, + Tracks: []model.QobuzTrack{{ISRC: "AAA"}}, + }}, + } + m := New(q, nil, 1) + matches, err := m.MatchAll(context.Background(), []*model.Album{album}) + if err != nil { + t.Fatal(err) + } + if match := matches["apple-1"]; match != nil { + t.Fatalf("expected no match, got %+v", match) + } +} + +func TestMatchRejectsDifferentArtist(t *testing.T) { + album := &model.Album{ + AppleID: "apple-1", + Title: "Sinking", + Artist: "Big Jesus Trash Can", + UPC: "111", + TrackCount: 1, + Year: 2026, + Tracks: []*model.Track{{ISRC: "AAA"}}, + } + q := &fakeQobuz{ + results: []model.QobuzAlbum{{ID: "q1", Title: "Sinking", Artist: "Beatrice M.", UPC: "222", TrackCount: 1, Year: 2026}}, + albums: map[string]model.QobuzAlbum{"q1": { + ID: "q1", Title: "Sinking", Artist: "Beatrice M.", TrackCount: 1, Year: 2026, + Tracks: []model.QobuzTrack{{ISRC: "BBB"}}, + }}, + } + m := New(q, nil, 1) + matches, err := m.MatchAll(context.Background(), []*model.Album{album}) + if err != nil { + t.Fatal(err) + } + if match := matches["apple-1"]; match != nil { + t.Fatalf("expected no match, got %+v", match) + } +} + +func TestUPCNormalization(t *testing.T) { + if got := normalizeUPC("0617308063523"); got != "617308063523" { + t.Fatalf("normalizeUPC = %q", got) + } + variants := upcVariants("617308063523") + if len(variants) == 0 || variants[0] != "0617308063523" { + t.Fatalf("variants = %#v", variants) + } +} diff --git a/internal/model/model.go b/internal/model/model.go new file mode 100644 index 0000000..827ef34 --- /dev/null +++ b/internal/model/model.go @@ -0,0 +1,105 @@ +// Package model contains the types shared between the Apple, Qobuz, matcher, +// library and m3u packages. +package model + +import "time" + +// Track is a track from an Apple Music playlist. +type Track struct { + AppleID string `json:"apple_id"` + Title string `json:"title"` + ArtistName string `json:"artist_name"` + Artists []string `json:"artists,omitempty"` + AlbumName string `json:"album_name"` + AlbumID string `json:"album_id"` + AlbumArtist string `json:"album_artist,omitempty"` + AlbumUPC string `json:"album_upc,omitempty"` + AlbumTrackCount int `json:"album_track_count,omitempty"` + AlbumReleaseDate string `json:"album_release_date,omitempty"` + ISRC string `json:"isrc,omitempty"` + DurationMS int `json:"duration_ms"` + TrackNumber int `json:"track_number,omitempty"` + DiscNumber int `json:"disc_number,omitempty"` + Explicit bool `json:"explicit,omitempty"` +} + +// Album is an Apple Music album referenced by one or more playlist tracks. +// Tracks contains only the tracks that occur in the playlist, not the full +// album. +type Album struct { + AppleID string `json:"apple_id"` + Title string `json:"title"` + Artist string `json:"artist"` + UPC string `json:"upc,omitempty"` + TrackCount int `json:"track_count,omitempty"` + ReleaseDate string `json:"release_date,omitempty"` + Year int `json:"year,omitempty"` + Tracks []*Track `json:"tracks"` +} + +// Playlist is the result of fetching one Apple Music playlist. +type Playlist struct { + URL string `json:"url"` + SourceID string `json:"source_id"` + Storefront string `json:"storefront"` + Name string `json:"name"` + Tracks []*Track `json:"tracks"` + Albums []*Album `json:"albums"` +} + +// QobuzTrack is a track from a Qobuz album. +type QobuzTrack struct { + ID int64 `json:"id"` + Title string `json:"title"` + ISRC string `json:"isrc,omitempty"` + TrackNumber int `json:"track_number,omitempty"` + DiscNumber int `json:"disc_number,omitempty"` + Duration int `json:"duration,omitempty"` +} + +// QobuzAlbum is an album returned by the Qobuz search or get endpoints. +type QobuzAlbum struct { + ID string `json:"id"` + Title string `json:"title"` + Artist string `json:"artist"` + UPC string `json:"upc,omitempty"` + Year int `json:"year,omitempty"` + TrackCount int `json:"track_count,omitempty"` + BitDepth int `json:"bit_depth,omitempty"` + SampleRate float64 `json:"sample_rate,omitempty"` + Tracks []QobuzTrack `json:"tracks,omitempty"` +} + +// AlbumMatch records how an Apple album was matched to Qobuz. +type AlbumMatch struct { + AppleAlbumID string `json:"apple_album_id"` + QobuzAlbumID string `json:"qobuz_album_id"` + QobuzTitle string `json:"qobuz_title"` + QobuzArtist string `json:"qobuz_artist"` + QobuzUPC string `json:"qobuz_upc,omitempty"` + QobuzTrackCount int `json:"qobuz_track_count,omitempty"` + Method string `json:"method"` // upc, fuzzy, isrc + Confidence float64 `json:"confidence"` + CheckedAt time.Time `json:"checked_at"` +} + +// CachedMatch is the persisted form of an album match lookup. A nil Match with +// a non-empty Error is a negative cache entry. +type CachedMatch struct { + Match *AlbumMatch `json:"match,omitempty"` + Error string `json:"error,omitempty"` + CheckedAt time.Time `json:"checked_at"` +} + +// FileEntry is one tagged audio file discovered in the download library. +type FileEntry struct { + Path string `json:"path"` + ISRC string `json:"isrc,omitempty"` + Title string `json:"title"` + Artist string `json:"artist"` + Album string `json:"album"` + AlbumArtist string `json:"album_artist,omitempty"` + TrackNumber int `json:"track_number,omitempty"` + DiscNumber int `json:"disc_number,omitempty"` + Format string `json:"format,omitempty"` +} diff --git a/internal/qobuz/client.go b/internal/qobuz/client.go new file mode 100644 index 0000000..062e95d --- /dev/null +++ b/internal/qobuz/client.go @@ -0,0 +1,303 @@ +// Package qobuz implements the small part of Qobuz's private API that +// applesync needs: album search and album detail. Only the public app id is +// required; no user login or request signing is used. +package qobuz + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "regexp" + "strconv" + "strings" + "sync" + "time" + + "applesync/internal/model" +) + +const ( + defaultBaseURL = "https://www.qobuz.com/api.json/0.2" + userAgent = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0 Safari/537.36" +) + +type Client struct { + http *http.Client + appID string + apiBase string + minDelay time.Duration + mu sync.Mutex + next time.Time + logf func(string, ...any) +} + +func New(appID string) *Client { + return &Client{ + http: &http.Client{Timeout: 30 * time.Second}, + appID: strings.TrimSpace(appID), + apiBase: defaultBaseURL, + minDelay: 150 * time.Millisecond, + } +} + +func (c *Client) SetLogf(fn func(string, ...any)) { c.logf = fn } + +func (c *Client) log(format string, args ...any) { + if c.logf != nil { + c.logf(format, args...) + } +} + +// ResolveAppID returns the configured app id, or scrapes the public one from +// play.qobuz.com if none was configured. +func ResolveAppID(ctx context.Context, configured string) (string, error) { + configured = strings.TrimSpace(configured) + if configured != "" { + return configured, nil + } + appID, err := scrapeAppID(ctx) + if err != nil { + return "", fmt.Errorf("Qobuz app id: %w; set [qobuz].app_id in the config", err) + } + return appID, nil +} + +func scrapeAppID(ctx context.Context) (string, error) { + hc := &http.Client{Timeout: 30 * time.Second} + login, err := fetchText(ctx, hc, "https://play.qobuz.com/login") + if err != nil { + return "", err + } + bundleRe := regexp.MustCompile(``) + match := bundleRe.FindStringSubmatch(login) + if len(match) < 2 { + return "", fmt.Errorf("could not find Qobuz bundle script") + } + bundle, err := fetchText(ctx, hc, "https://play.qobuz.com"+match[1]) + if err != nil { + return "", err + } + appIDRe := regexp.MustCompile(`production:{api:{appId:"(\d{9})"`) + appMatch := appIDRe.FindStringSubmatch(bundle) + if len(appMatch) < 2 { + return "", fmt.Errorf("could not parse Qobuz app id from bundle") + } + return appMatch[1], nil +} + +func fetchText(ctx context.Context, hc *http.Client, rawURL string) (string, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil) + if err != nil { + return "", err + } + req.Header.Set("User-Agent", userAgent) + resp, err := hc.Do(req) + if err != nil { + return "", err + } + defer resp.Body.Close() + if resp.StatusCode >= 300 { + return "", fmt.Errorf("%s: status %d", rawURL, resp.StatusCode) + } + data, err := io.ReadAll(io.LimitReader(resp.Body, 16<<20)) + if err != nil { + return "", err + } + return string(data), nil +} + +// SearchAlbums searches Qobuz albums. +func (c *Client) SearchAlbums(ctx context.Context, query string, limit int) ([]model.QobuzAlbum, error) { + if limit <= 0 { + limit = 10 + } + params := url.Values{} + params.Set("query", query) + params.Set("limit", strconv.Itoa(limit)) + var resp searchResponse + if err := c.get(ctx, "/album/search", params, &resp); err != nil { + return nil, err + } + albums := make([]model.QobuzAlbum, 0, len(resp.Albums.Items)) + for _, item := range resp.Albums.Items { + album := model.QobuzAlbum{ + ID: strings.TrimSpace(item.ID), + Title: strings.TrimSpace(item.Title), + Artist: strings.TrimSpace(item.Artist.Name), + UPC: strings.TrimSpace(item.UPC), + Year: yearFromDate(item.ReleaseDateOriginal), + TrackCount: item.TracksCount, + BitDepth: item.MaximumBitDepth, + SampleRate: item.MaximumSamplingRate, + } + if album.ID != "" && album.Title != "" { + albums = append(albums, album) + } + } + return albums, nil +} + +// GetAlbum fetches one album including its track list and ISRCs. +func (c *Client) GetAlbum(ctx context.Context, albumID string) (*model.QobuzAlbum, error) { + params := url.Values{} + params.Set("album_id", albumID) + var resp albumResponse + if err := c.get(ctx, "/album/get", params, &resp); err != nil { + return nil, err + } + album := &model.QobuzAlbum{ + ID: strings.TrimSpace(resp.ID), + Title: strings.TrimSpace(resp.Title), + Artist: strings.TrimSpace(resp.Artist.Name), + UPC: strings.TrimSpace(resp.UPC), + Year: yearFromDate(resp.ReleaseDateOriginal), + TrackCount: resp.TracksCount, + BitDepth: resp.MaximumBitDepth, + SampleRate: resp.MaximumSamplingRate, + } + for _, t := range resp.Tracks.Items { + album.Tracks = append(album.Tracks, model.QobuzTrack{ + ID: t.ID, + Title: strings.TrimSpace(t.Title), + ISRC: strings.ToUpper(strings.TrimSpace(t.ISRC)), + TrackNumber: t.TrackNumber, + DiscNumber: t.MediaNumber, + Duration: t.Duration, + }) + } + return album, nil +} + +func yearFromDate(date string) int { + date = strings.TrimSpace(date) + if len(date) < 4 { + return 0 + } + year, err := strconv.Atoi(date[:4]) + if err != nil { + return 0 + } + return year +} + +func (c *Client) get(ctx context.Context, path string, params url.Values, out any) error { + if c.appID == "" { + return fmt.Errorf("qobuz app id is empty") + } + params.Set("app_id", c.appID) + endpoint := c.apiBase + path + "?" + params.Encode() + + var lastErr error + for attempt := 1; attempt <= 4; attempt++ { + if err := c.wait(ctx); err != nil { + return err + } + req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil) + if err != nil { + return err + } + req.Header.Set("User-Agent", userAgent) + req.Header.Set("X-App-Id", c.appID) + + resp, err := c.http.Do(req) + if err != nil { + lastErr = err + sleep(ctx, time.Duration(attempt)*500*time.Millisecond) + continue + } + if resp.StatusCode == http.StatusTooManyRequests || resp.StatusCode >= 500 { + _ = resp.Body.Close() + lastErr = fmt.Errorf("qobuz api status %d", resp.StatusCode) + sleep(ctx, time.Duration(attempt)*time.Second) + continue + } + if resp.StatusCode >= 300 { + body, _ := io.ReadAll(io.LimitReader(resp.Body, 4096)) + _ = resp.Body.Close() + return fmt.Errorf("qobuz api error (%d): %s", resp.StatusCode, strings.TrimSpace(string(body))) + } + if err := json.NewDecoder(resp.Body).Decode(out); err != nil { + _ = resp.Body.Close() + return err + } + _ = resp.Body.Close() + return nil + } + if lastErr == nil { + lastErr = fmt.Errorf("qobuz request failed after retries") + } + return lastErr +} + +func (c *Client) wait(ctx context.Context) error { + c.mu.Lock() + now := time.Now() + wait := time.Duration(0) + if now.Before(c.next) { + wait = c.next.Sub(now) + c.next = c.next.Add(c.minDelay) + } else { + c.next = now.Add(c.minDelay) + } + c.mu.Unlock() + if wait > 0 { + sleep(ctx, wait) + } + return ctx.Err() +} + +func sleep(ctx context.Context, d time.Duration) { + timer := time.NewTimer(d) + defer timer.Stop() + select { + case <-ctx.Done(): + case <-timer.C: + } +} + +type searchResponse struct { + Albums struct { + Items []searchAlbum `json:"items"` + Total int `json:"total"` + } `json:"albums"` +} + +type searchAlbum struct { + ID string `json:"id"` + Title string `json:"title"` + Artist artist `json:"artist"` + Year int `json:"year"` + TracksCount int `json:"tracks_count"` + UPC string `json:"upc"` + ReleaseDateOriginal string `json:"release_date_original"` + MaximumBitDepth int `json:"maximum_bit_depth"` + MaximumSamplingRate float64 `json:"maximum_sampling_rate"` +} + +type albumResponse struct { + ID string `json:"id"` + Title string `json:"title"` + Artist artist `json:"artist"` + UPC string `json:"upc"` + ReleaseDateOriginal string `json:"release_date_original"` + TracksCount int `json:"tracks_count"` + MaximumBitDepth int `json:"maximum_bit_depth"` + MaximumSamplingRate float64 `json:"maximum_sampling_rate"` + Tracks struct { + Items []struct { + ID int64 `json:"id"` + Title string `json:"title"` + TrackNumber int `json:"track_number"` + MediaNumber int `json:"media_number"` + ISRC string `json:"isrc"` + Duration int `json:"duration"` + } `json:"items"` + } `json:"tracks"` +} + +type artist struct { + Name string `json:"name"` +} diff --git a/internal/qobuz/client_test.go b/internal/qobuz/client_test.go new file mode 100644 index 0000000..910260e --- /dev/null +++ b/internal/qobuz/client_test.go @@ -0,0 +1,54 @@ +package qobuz + +import ( + "context" + "net/http" + "net/http/httptest" + "testing" +) + +func TestSearchAndGetAlbum(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if got := r.URL.Query().Get("app_id"); got != "123" { + t.Errorf("app_id = %q", got) + } + switch r.URL.Path { + case "/album/search": + if r.URL.Query().Get("query") != "Popfly" { + t.Errorf("query = %q", r.URL.Query().Get("query")) + } + _, _ = w.Write([]byte(`{"albums":{"items":[{"id":"q1","title":"Popfly","artist":{"name":"Michael Nau"},"tracks_count":10,"upc":"0617308063523","release_date_original":"2026-10-23","maximum_bit_depth":24,"maximum_sampling_rate":96}],"total":1}}`)) + case "/album/get": + if r.URL.Query().Get("album_id") != "q1" { + t.Errorf("album_id = %q", r.URL.Query().Get("album_id")) + } + _, _ = w.Write([]byte(`{"id":"q1","title":"Popfly","artist":{"name":"Michael Nau"},"upc":"0617308063523","release_date_original":"2026-10-23","tracks_count":2,"tracks":{"items":[{"id":1,"title":"Lost Station Hideaway","track_number":1,"media_number":1,"isrc":"us33x2624501","duration":250},{"id":2,"title":"Hi Beam","track_number":2,"media_number":1,"isrc":"US33X2624502","duration":193}]}}`)) + default: + http.NotFound(w, r) + } + })) + defer server.Close() + + client := &Client{http: server.Client(), appID: "123", apiBase: server.URL} + albums, err := client.SearchAlbums(context.Background(), "Popfly", 10) + if err != nil { + t.Fatal(err) + } + if len(albums) != 1 { + t.Fatalf("albums = %d", len(albums)) + } + if albums[0].ID != "q1" || albums[0].Artist != "Michael Nau" || albums[0].TrackCount != 10 || albums[0].Year != 2026 { + t.Fatalf("unexpected album: %+v", albums[0]) + } + + full, err := client.GetAlbum(context.Background(), "q1") + if err != nil { + t.Fatal(err) + } + if full.Title != "Popfly" || len(full.Tracks) != 2 { + t.Fatalf("unexpected album: %+v", full) + } + if full.Tracks[0].ISRC != "US33X2624501" || full.Tracks[0].TrackNumber != 1 { + t.Fatalf("unexpected track: %+v", full.Tracks[0]) + } +} diff --git a/internal/report/report.go b/internal/report/report.go new file mode 100644 index 0000000..48f943c --- /dev/null +++ b/internal/report/report.go @@ -0,0 +1,57 @@ +// Package report writes an optional JSON run report. +package report + +import ( + "encoding/json" + "time" + + "applesync/internal/state" +) + +type Report struct { + GeneratedAt time.Time `json:"generated_at"` + RipError string `json:"rip_error,omitempty"` + AlbumsToDownload int `json:"albums_to_download"` + AlbumsPresent int `json:"albums_present"` + Playlists []PlaylistReport `json:"playlists"` +} + +type PlaylistReport struct { + Name string `json:"name"` + URL string `json:"url"` + Mode string `json:"mode"` + M3UPath string `json:"m3u_path,omitempty"` + TracksTotal int `json:"tracks_total"` + AlbumsTotal int `json:"albums_total"` + AlbumsMatched int `json:"albums_matched"` + AlbumsUnmatched int `json:"albums_unmatched"` + TracksWritten int `json:"tracks_written"` + TracksMissing int `json:"tracks_missing"` + UnmatchedAlbums []AlbumIssue `json:"unmatched_albums,omitempty"` + MissingTracks []TrackIssue `json:"missing_tracks,omitempty"` + Error string `json:"error,omitempty"` +} + +type AlbumIssue struct { + Artist string `json:"artist"` + Title string `json:"title"` + UPC string `json:"upc,omitempty"` + Reason string `json:"reason,omitempty"` +} + +type TrackIssue struct { + Artist string `json:"artist"` + Title string `json:"title"` + Album string `json:"album,omitempty"` + ISRC string `json:"isrc,omitempty"` + Reason string `json:"reason,omitempty"` +} + +func Write(path string, r *Report) error { + data, err := json.MarshalIndent(r, "", " ") + if err != nil { + return err + } + data = append(data, '\n') + return state.WriteFileAtomic(path, data) +} diff --git a/internal/rip/rip.go b/internal/rip/rip.go new file mode 100644 index 0000000..f99007d --- /dev/null +++ b/internal/rip/rip.go @@ -0,0 +1,181 @@ +// Package rip wraps the external streamrip-go binary. Downloads are always +// delegated to rip so its Qobuz login, quality settings, conversion settings +// and download database remain authoritative. +package rip + +import ( + "context" + "encoding/json" + "fmt" + "os" + "os/exec" + "path/filepath" + "regexp" + "strconv" + "strings" + + "github.com/BurntSushi/toml" + + "applesync/internal/state" +) + +type Runner struct { + Binary string + ConfigPath string + Quality int + Codec string + Folder string + ExtraArgs []string + NoProgress bool + StateDir string + Logf func(string, ...any) +} + +func (r *Runner) log(format string, args ...any) { + if r.Logf != nil { + r.Logf(format, args...) + } +} + +// Available verifies that the rip binary exists. +func (r *Runner) Available() error { + binary := strings.TrimSpace(r.Binary) + if binary == "" { + return fmt.Errorf("rip binary is not configured") + } + if strings.Contains(binary, "/") { + info, err := os.Stat(binary) + if err != nil { + return fmt.Errorf("rip binary %s: %w", binary, err) + } + if info.IsDir() { + return fmt.Errorf("rip binary %s is a directory", binary) + } + return nil + } + if _, err := exec.LookPath(binary); err != nil { + return fmt.Errorf("rip binary %q not found in PATH: %w", binary, err) + } + return nil +} + +func (r *Runner) globalArgs() []string { + args := make([]string, 0, 12) + if r.NoProgress { + args = append(args, "--no-progress") + } + if r.ConfigPath != "" { + args = append(args, "--config-path", r.ConfigPath) + } + if r.Quality >= 0 { + args = append(args, "-q", strconv.Itoa(r.Quality)) + } + if strings.TrimSpace(r.Codec) != "" { + args = append(args, "-c", strings.TrimSpace(r.Codec)) + } + if r.Folder != "" { + args = append(args, "-f", r.Folder) + } + args = append(args, r.ExtraArgs...) + return args +} + +type batchItem struct { + Source string `json:"source"` + MediaType string `json:"media_type"` + ID string `json:"id"` +} + +// DownloadAlbums writes a streamrip-go batch file and runs `rip file` on it. +func (r *Runner) DownloadAlbums(ctx context.Context, albumIDs []string, force bool) error { + ids := uniqueIDs(albumIDs) + if len(ids) == 0 { + return nil + } + if err := r.Available(); err != nil { + return err + } + if err := os.MkdirAll(r.StateDir, 0o755); err != nil { + return err + } + items := make([]batchItem, 0, len(ids)) + for _, id := range ids { + items = append(items, batchItem{Source: "qobuz", MediaType: "album", ID: id}) + } + data, err := json.MarshalIndent(items, "", " ") + if err != nil { + return err + } + batchPath := filepath.Join(r.StateDir, "qobuz_batch.json") + if err := state.WriteFileAtomic(batchPath, data); err != nil { + return err + } + args := append(r.globalArgs(), "file", batchPath) + if force { + args = append(args, "--force") + } + r.log("rip: %s %s", r.Binary, strings.Join(args, " ")) + cmd := exec.CommandContext(ctx, r.Binary, args...) + cmd.Stdout = os.Stdout + cmd.Stderr = os.Stderr + if err := cmd.Run(); err != nil { + return fmt.Errorf("rip file failed: %w", err) + } + return nil +} + +func uniqueIDs(ids []string) []string { + seen := map[string]bool{} + out := make([]string, 0, len(ids)) + for _, id := range ids { + id = strings.TrimSpace(id) + if id == "" || seen[id] { + continue + } + seen[id] = true + out = append(out, id) + } + return out +} + +var quotedPathRe = regexp.MustCompile(`['"]([^'"]+)['"]`) + +// ResolveConfigPath asks rip where its config lives. +func (r *Runner) ResolveConfigPath(ctx context.Context) (string, error) { + if r.ConfigPath != "" { + return r.ConfigPath, nil + } + if err := r.Available(); err != nil { + return "", err + } + out, err := exec.CommandContext(ctx, r.Binary, "config", "path").CombinedOutput() + if err != nil { + return "", fmt.Errorf("rip config path: %w: %s", err, strings.TrimSpace(string(out))) + } + textOut := strings.TrimSpace(string(out)) + if match := quotedPathRe.FindStringSubmatch(textOut); len(match) > 1 { + return state.ExpandPath(match[1]), nil + } + if _, after, ok := strings.Cut(textOut, "path:"); ok { + return state.ExpandPath(strings.TrimSpace(after)), nil + } + return "", fmt.Errorf("could not parse rip config path from %q", textOut) +} + +// QobuzAppID reads the public app id that rip has already bootstrapped into its +// config. This avoids scraping play.qobuz.com on every run. +func (r *Runner) QobuzAppID(ctx context.Context) (string, error) { + path, err := r.ResolveConfigPath(ctx) + if err != nil { + return "", err + } + var cfg struct { + Qobuz struct { + AppID string `toml:"app_id"` + } `toml:"qobuz"` + } + if _, err := toml.DecodeFile(path, &cfg); err != nil { + return "", fmt.Errorf("read rip config %s: %w", path, err) + } + return strings.TrimSpace(cfg.Qobuz.AppID), nil +} diff --git a/internal/rip/rip_test.go b/internal/rip/rip_test.go new file mode 100644 index 0000000..b94f025 --- /dev/null +++ b/internal/rip/rip_test.go @@ -0,0 +1,72 @@ +package rip + +import ( + "context" + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" +) + +func TestDownloadAlbumsBuildsBatchAndArgs(t *testing.T) { + dir := t.TempDir() + script := filepath.Join(dir, "fake-rip") + content := `#!/bin/sh +printf '%s\n' "$@" > "$0.args" +prev="" +for a in "$@"; do + if [ "$prev" = "file" ]; then cp "$a" "$0.batch"; fi + prev="$a" +done +` + if err := os.WriteFile(script, []byte(content), 0o755); err != nil { + t.Fatal(err) + } + + runner := &Runner{ + Binary: script, + Quality: 3, + Folder: "/tmp/music", + ExtraArgs: []string{"--no-ssl-verify"}, + NoProgress: true, + StateDir: dir, + } + if err := runner.DownloadAlbums(context.Background(), []string{"id1", "id2", "id1"}, false); err != nil { + t.Fatal(err) + } + + args, err := os.ReadFile(script + ".args") + if err != nil { + t.Fatal(err) + } + argList := strings.Split(strings.TrimSpace(string(args)), "\n") + wantArgs := []string{"--no-progress", "-q", "3", "-f", "/tmp/music", "--no-ssl-verify", "file"} + for i, want := range wantArgs { + if i >= len(argList) || argList[i] != want { + t.Fatalf("args = %#v, want prefix %#v", argList, wantArgs) + } + } + + data, err := os.ReadFile(script + ".batch") + if err != nil { + t.Fatal(err) + } + var items []batchItem + if err := json.Unmarshal(data, &items); err != nil { + t.Fatal(err) + } + if len(items) != 2 || items[0].ID != "id1" || items[1].ID != "id2" { + t.Fatalf("unexpected batch: %+v", items) + } + if items[0].Source != "qobuz" || items[0].MediaType != "album" { + t.Fatalf("unexpected item: %+v", items[0]) + } +} + +func TestUniqueIDs(t *testing.T) { + got := uniqueIDs([]string{"a", "b", "a", " ", "c"}) + if len(got) != 3 || got[0] != "a" || got[2] != "c" { + t.Fatalf("uniqueIDs = %#v", got) + } +} diff --git a/internal/state/state.go b/internal/state/state.go new file mode 100644 index 0000000..ad19834 --- /dev/null +++ b/internal/state/state.go @@ -0,0 +1,174 @@ +// Package state persists the Qobuz match cache and provides a run lock. +package state + +import ( + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "strconv" + "sync" + "time" + + "applesync/internal/model" +) + +// ExpandPath expands a leading ~ using the current user's home directory. +func ExpandPath(path string) string { + if path == "" || path[0] != '~' { + return path + } + home, err := os.UserHomeDir() + if err != nil { + return path + } + if path == "~" { + return home + } + if len(path) > 1 && path[1] == '/' { + return filepath.Join(home, path[2:]) + } + return path +} + +// WriteFileAtomic writes data to path via a temporary file and rename. +func WriteFileAtomic(path string, data []byte) error { + dir := filepath.Dir(path) + if err := os.MkdirAll(dir, 0o755); err != nil { + return err + } + f, err := os.CreateTemp(dir, filepath.Base(path)+".*.tmp") + if err != nil { + return err + } + tmp := f.Name() + defer func() { _ = os.Remove(tmp) }() + if _, err := f.Write(data); err != nil { + _ = f.Close() + return err + } + if err := f.Close(); err != nil { + return err + } + return os.Rename(tmp, path) +} + +// MatchCache is a concurrency-safe JSON cache of Apple album -> Qobuz match +// lookups. +type MatchCache struct { + mu sync.Mutex + path string + entries map[string]model.CachedMatch + dirty bool +} + +type cacheFile struct { + Version int `json:"version"` + Entries map[string]model.CachedMatch `json:"entries"` +} + +// LoadMatchCache loads (or creates) the cache at path. +func LoadMatchCache(path string) (*MatchCache, error) { + c := &MatchCache{path: path, entries: map[string]model.CachedMatch{}} + data, err := os.ReadFile(path) + if errors.Is(err, os.ErrNotExist) { + return c, nil + } + if err != nil { + return nil, err + } + var file cacheFile + if err := json.Unmarshal(data, &file); err != nil { + // A corrupt cache should not stop a sync; start fresh. + return c, nil + } + if file.Entries != nil { + c.entries = file.Entries + } + return c, nil +} + +// Get returns a cached entry if it is still fresh. +func (c *MatchCache) Get(appleAlbumID string) (model.CachedMatch, bool) { + c.mu.Lock() + defer c.mu.Unlock() + entry, ok := c.entries[appleAlbumID] + if !ok { + return model.CachedMatch{}, false + } + ttl := 90 * 24 * time.Hour + if entry.Match == nil { + ttl = 7 * 24 * time.Hour + } + if time.Since(entry.CheckedAt) > ttl { + return model.CachedMatch{}, false + } + return entry, true +} + +// Put stores an entry and marks the cache dirty. +func (c *MatchCache) Put(appleAlbumID string, entry model.CachedMatch) { + c.mu.Lock() + defer c.mu.Unlock() + c.entries[appleAlbumID] = entry + c.dirty = true +} + +// Save writes the cache atomically if it changed. +func (c *MatchCache) Save() error { + c.mu.Lock() + defer c.mu.Unlock() + if !c.dirty { + return nil + } + data, err := json.MarshalIndent(cacheFile{Version: 1, Entries: c.entries}, "", " ") + if err != nil { + return err + } + if err := WriteFileAtomic(c.path, data); err != nil { + return err + } + c.dirty = false + return nil +} + +// Lock is an exclusive run lock. +type Lock struct { + path string +} + +// AcquireLock creates an exclusive lock in dir. A lock older than 24 hours is +// considered stale and is replaced. +func AcquireLock(dir string) (*Lock, error) { + if err := os.MkdirAll(dir, 0o755); err != nil { + return nil, err + } + path := filepath.Join(dir, "applesync.lock") + for attempt := 0; attempt < 2; attempt++ { + f, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o644) + if err == nil { + _, _ = fmt.Fprintf(f, "pid=%d\nstarted=%s\n", os.Getpid(), time.Now().Format(time.RFC3339)) + _ = f.Close() + return &Lock{path: path}, nil + } + if !errors.Is(err, os.ErrExist) { + return nil, err + } + info, statErr := os.Stat(path) + if statErr == nil && time.Since(info.ModTime()) > 24*time.Hour { + _ = os.Remove(path) + continue + } + data, _ := os.ReadFile(path) + return nil, fmt.Errorf("another applesync run holds the lock %s (%s)", path, strconv.Quote(string(data))) + } + return nil, fmt.Errorf("could not acquire lock %s", path) +} + +// Release removes the lock file. +func (l *Lock) Release() { + if l != nil { + _ = os.Remove(l.path) + } +} diff --git a/internal/state/state_test.go b/internal/state/state_test.go new file mode 100644 index 0000000..6e85c3e --- /dev/null +++ b/internal/state/state_test.go @@ -0,0 +1,58 @@ +package state + +import ( + "path/filepath" + "testing" + "time" + + "applesync/internal/model" +) + +func TestMatchCacheRoundTrip(t *testing.T) { + path := filepath.Join(t.TempDir(), "cache.json") + cache, err := LoadMatchCache(path) + if err != nil { + t.Fatal(err) + } + cache.Put("album-1", model.CachedMatch{ + Match: &model.AlbumMatch{QobuzAlbumID: "q1", Method: "upc"}, + CheckedAt: time.Now(), + }) + if err := cache.Save(); err != nil { + t.Fatal(err) + } + reloaded, err := LoadMatchCache(path) + if err != nil { + t.Fatal(err) + } + entry, ok := reloaded.Get("album-1") + if !ok || entry.Match == nil || entry.Match.QobuzAlbumID != "q1" { + t.Fatalf("unexpected entry: %+v ok=%v", entry, ok) + } +} + +func TestNegativeCacheExpires(t *testing.T) { + path := filepath.Join(t.TempDir(), "cache.json") + cache, _ := LoadMatchCache(path) + cache.Put("album-1", model.CachedMatch{Error: "no match", CheckedAt: time.Now().Add(-8 * 24 * time.Hour)}) + if _, ok := cache.Get("album-1"); ok { + t.Fatal("negative entry older than 7 days should expire") + } +} + +func TestLock(t *testing.T) { + dir := t.TempDir() + lock, err := AcquireLock(dir) + if err != nil { + t.Fatal(err) + } + if _, err := AcquireLock(dir); err == nil { + t.Fatal("expected second lock to fail") + } + lock.Release() + lock2, err := AcquireLock(dir) + if err != nil { + t.Fatalf("lock after release: %v", err) + } + lock2.Release() +} diff --git a/internal/text/text.go b/internal/text/text.go new file mode 100644 index 0000000..baabef2 --- /dev/null +++ b/internal/text/text.go @@ -0,0 +1,189 @@ +// Package text provides the normalization and fuzzy-matching helpers shared by +// the matcher and library packages. It is adapted from LastRecc's text package +// so that the same titles match across both tools. +package text + +import ( + "fmt" + "regexp" + "strings" + "unicode" +) + +var ( + parenRe = regexp.MustCompile(`\([^)]*\)|\[[^\]]*\]`) + featRe = regexp.MustCompile(`(?i)\b(feat\.?|ft\.?|featuring|with)\b.*$`) + albumSuffixRe = regexp.MustCompile(`(?i)\s+-\s+(single|ep|album)$`) + trailingBracket = regexp.MustCompile(`(?i)\s*[\(\[]([^\)\]]*)[\)\]]\s*$`) + descriptiveRe = regexp.MustCompile(`(?i)\s+-\s+(deluxe|deluxe edition|expanded|expanded edition|remastered|remastered edition|bonus track version|special edition)$`) + noisePhrases = []string{ + "live", "concert", "greatest hits", "best of", "compilation", + "anthology", "collection", "essential", "hits", "remix", "remixes", + "tribute", "karaoke", "instrumental", "cover", "edits", + "концерт", "живой", "сборник", "лучшее", "хиты", + "антология", "коллекция", "избранное", "ремикс", "караоке", + "инструментал", "дискография", "трибьют", "кавер", + } +) + +// Normalize lowercases a string, drops parentheses/brackets, feature credits +// and punctuation, and collapses whitespace. +func Normalize(value string) string { + value = strings.ToLower(value) + value = parenRe.ReplaceAllString(value, " ") + value = featRe.ReplaceAllString(value, " ") + var b strings.Builder + space := true + for _, r := range value { + if unicode.IsLetter(r) || unicode.IsDigit(r) { + b.WriteRune(r) + space = false + } else if !space { + b.WriteRune(' ') + space = true + } + } + return strings.TrimSpace(b.String()) +} + +// CleanAlbumTitle strips Apple's " - Single" / " - EP" / " - Album" suffixes. +func CleanAlbumTitle(value string) string { + return strings.TrimSpace(albumSuffixRe.ReplaceAllString(strings.TrimSpace(value), "")) +} + +// SearchTitle additionally strips trailing parenthetical and edition suffixes +// such as "(Deluxe)", "(Remastered)" or " - Deluxe Edition". It is used to +// build Qobuz search queries; matching still normalizes punctuation separately. +func SearchTitle(value string) string { + s := CleanAlbumTitle(value) + for { + trimmed := trailingBracket.ReplaceAllString(s, "") + trimmed = descriptiveRe.ReplaceAllString(trimmed, "") + trimmed = strings.TrimSpace(trimmed) + if trimmed == s || trimmed == "" { + break + } + s = trimmed + } + return s +} + +// TrackKey builds a normalized artist::title key. +func TrackKey(artist, title string) string { + return Normalize(artist) + "::" + Normalize(title) +} + +// AlbumKey builds a normalized artist::album key. +func AlbumKey(artist, album string) string { + return Normalize(artist) + "::" + Normalize(album) +} + +// Similarity returns a normalized Levenshtein similarity in [0, 1]. +func Similarity(a, b string) float64 { + a = Normalize(a) + b = Normalize(b) + if a == "" && b == "" { + return 1 + } + if a == "" || b == "" { + return 0 + } + if a == b { + return 1 + } + distance := levenshtein([]rune(a), []rune(b)) + maxLen := len([]rune(a)) + if len([]rune(b)) > maxLen { + maxLen = len([]rune(b)) + } + if maxLen == 0 { + return 1 + } + return 1 - float64(distance)/float64(maxLen) +} + +func levenshtein(a, b []rune) int { + if len(a) == 0 { + return len(b) + } + if len(b) == 0 { + return len(a) + } + prev := make([]int, len(b)+1) + for j := range prev { + prev[j] = j + } + for i := 1; i <= len(a); i++ { + cur := make([]int, len(b)+1) + cur[0] = i + for j := 1; j <= len(b); j++ { + cost := 1 + if a[i-1] == b[j-1] { + cost = 0 + } + cur[j] = min3(cur[j-1]+1, prev[j]+1, prev[j-1]+cost) + } + prev = cur + } + return prev[len(b)] +} + +func min3(a, b, c int) int { + if a < b { + if a < c { + return a + } + return c + } + if b < c { + return b + } + return c +} + +// IsNoisyAlbum reports whether an album title looks like a compilation, live +// album, remix collection, etc. +func IsNoisyAlbum(name string) bool { + lower := strings.ToLower(name) + replacer := strings.NewReplacer("(", " ", ")", " ", "[", " ", "]", " ", "-", " ", "—", " ") + padded := " " + replacer.Replace(lower) + " " + for _, phrase := range noisePhrases { + if strings.Contains(padded, " "+phrase) { + return true + } + } + return false +} + +// Slug converts a playlist name into a safe file name stem. +func Slug(value string) string { + value = strings.ToLower(strings.TrimSpace(value)) + var b strings.Builder + lastDash := true + for _, r := range value { + if unicode.IsLetter(r) || unicode.IsDigit(r) { + b.WriteRune(r) + lastDash = false + } else if !lastDash { + b.WriteRune('-') + lastDash = true + } + } + out := strings.Trim(b.String(), "-") + if out == "" { + out = "playlist" + } + if len([]rune(out)) > 80 { + out = string([]rune(out)[:80]) + out = strings.TrimRight(out, "-") + } + return out +} + +// FormatDuration renders seconds as m:ss. +func FormatDuration(seconds int) string { + if seconds <= 0 { + return "" + } + return fmt.Sprintf("%d:%02d", seconds/60, seconds%60) +} diff --git a/internal/text/text_test.go b/internal/text/text_test.go new file mode 100644 index 0000000..b3dd82a --- /dev/null +++ b/internal/text/text_test.go @@ -0,0 +1,45 @@ +package text + +import "testing" + +func TestSearchTitle(t *testing.T) { + cases := map[string]string{ + "The X-panded Universe - Single": "The X-panded Universe", + "Ambiguous Desire (Deluxe)": "Ambiguous Desire", + "Album - Deluxe Edition": "Album", + "Song (Remastered)": "Song", + "Untouched": "Untouched", + } + for input, want := range cases { + if got := SearchTitle(input); got != want { + t.Errorf("SearchTitle(%q) = %q, want %q", input, got, want) + } + } +} + +func TestSimilarityEmptyArtists(t *testing.T) { + if got := Similarity("@", "@"); got != 1 { + t.Fatalf("Similarity(@,@) = %v, want 1", got) + } + if got := Similarity("@", "Someone"); got != 0 { + t.Fatalf("Similarity(@,Someone) = %v, want 0", got) + } +} + +func TestSlug(t *testing.T) { + if got := Slug("indie + chill"); got != "indie-chill" { + t.Fatalf("Slug = %q", got) + } + if got := Slug(" *** "); got != "playlist" { + t.Fatalf("Slug fallback = %q", got) + } +} + +func TestIsNoisyAlbum(t *testing.T) { + if !IsNoisyAlbum("Greatest Hits") { + t.Fatal("expected Greatest Hits to be noisy") + } + if IsNoisyAlbum("Popfly") { + t.Fatal("Popfly should not be noisy") + } +}