Files
AppleSync/internal/rip/rip.go
T
2026-11-26 15:11:41 +01:00

182 lines
4.5 KiB
Go

// 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
}