package rip import ( "context" "errors" "fmt" "os" "os/exec" "path/filepath" "regexp" "strconv" "strings" "time" "lastrecc-go/internal/cache" "lastrecc-go/internal/text" ) var idLineRe = regexp.MustCompile(`(?m)^\s*\d+\.\s+id=([A-Za-z0-9]+)\s+\|\s+(.+?)\s*$`) type Hit struct { ID string Title string Score float64 } type Runner struct { Binary string ConfigPath string Quality int SearchDelay time.Duration StateDir string Logf func(string, ...any) } func (r *Runner) logf(format string, args ...any) { if r.Logf != nil { r.Logf(format, args...) } } func (r *Runner) Available() bool { if r.Binary == "" { return false } if strings.Contains(r.Binary, "/") { info, err := os.Stat(r.Binary) return err == nil && !info.IsDir() } _, err := exec.LookPath(r.Binary) return err == nil } func (r *Runner) globalArgs() []string { args := []string{"--no-progress"} if r.ConfigPath != "" { args = append(args, "--config-path", r.ConfigPath) } if r.Quality >= 0 { args = append(args, "-q", strconv.Itoa(r.Quality)) } return args } func (r *Runner) search(ctx context.Context, query string) ([]Hit, error) { searchCtx, cancel := context.WithTimeout(ctx, 90*time.Second) defer cancel() args := append(r.globalArgs(), "search", "qobuz", "album", query, "--no-download", "--first") cmd := exec.CommandContext(searchCtx, r.Binary, args...) output, err := cmd.CombinedOutput() if err != nil { return nil, fmt.Errorf("rip search failed: %w: %s", err, truncate(string(output), 500)) } return parseSearchOutput(string(output)), nil } func parseSearchOutput(output string) []Hit { if strings.Contains(strings.ToLower(output), "no results") { return nil } matches := idLineRe.FindAllStringSubmatch(output, -1) hits := make([]Hit, 0, len(matches)) seen := map[string]bool{} for _, match := range matches { id := match[1] if seen[id] { continue } seen[id] = true hits = append(hits, Hit{ID: id, Title: strings.TrimSpace(match[2])}) } return hits } // SearchAlbum checks Qobuz for the album and returns the best title match. func (r *Runner) SearchAlbum(ctx context.Context, artist, album string) (*Hit, error) { if r.SearchDelay > 0 { timer := time.NewTimer(r.SearchDelay) select { case <-ctx.Done(): timer.Stop() return nil, ctx.Err() case <-timer.C: } } queries := []string{artist + " " + album, album + " " + artist, album} var best *Hit for _, query := range queries { hits, err := r.search(ctx, query) if err != nil { return nil, err } for _, hit := range hits { if text.IsNoisyAlbum(hit.Title) { continue } score := text.Similarity(hit.Title, album) if best == nil || score > best.Score { candidate := hit candidate.Score = score best = &candidate } } if best != nil && best.Score >= 0.9 { break } } if best == nil || best.Score < 0.9 { return nil, nil } return best, nil } type batchItem struct { Source string `json:"source"` MediaType string `json:"media_type"` ID string `json:"id"` } // DownloadAlbums writes a batch file and lets streamrip-go fetch all albums // with its own config (Qobuz auth, quality, destination folder, dedupe DB). func (r *Runner) DownloadAlbums(ctx context.Context, hits []Hit) error { if len(hits) == 0 { return nil } items := make([]batchItem, 0, len(hits)) for _, hit := range hits { items = append(items, batchItem{Source: "qobuz", MediaType: "album", ID: hit.ID}) } if err := os.MkdirAll(r.StateDir, 0o755); err != nil { return err } batchPath := filepath.Join(r.StateDir, "qobuz_batch.json") if err := cache.SaveJSON(batchPath, items); err != nil { return err } args := append(r.globalArgs(), "file", batchPath) r.logf("running %s %s", r.Binary, strings.Join(args, " ")) cmd := exec.CommandContext(ctx, r.Binary, args...) cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr return cmd.Run() } func truncate(value string, limit int) string { if len(value) <= limit { return value } return value[:limit] + "…" } var _ = errors.New