Files
streamrip-go/cmd/rip/args.go
T
JorenandClaude Opus 5 201aa5daa7 fix: database migration, config validation and provider client defects
Completes the correctness pass.

Download database migration no longer destroys dedupe state
  The pre-source-column migration carried every legacy row over with
  source='' and then dropped downloads_legacy, while IsDownloaded matched
  source exactly. The result was that every previously recorded download
  looked new, the user silently re-downloaded their whole library, and the
  original rows were gone. Now the file is copied to <path>.bak-<unixtime>
  first, downloads_legacy is kept, and IsDownloaded falls back to the
  sourceless rows (over-matching across sources costs a skipped re-download,
  which is the cheaper error). Schema state is tracked in PRAGMA user_version
  so later migrations can be ordered explicitly. Databases already migrated by
  the old code are detected on open.

  Also enables WAL and a 10s busy_timeout and caps the pool at one connection,
  so a concurrent reader no longer gets SQLITE_BUSY with no retry, and builds
  the DSN through url.URL so a path containing '?' is not parsed as query
  parameters.

--quality now applies to every source
  applyGlobalConfigOverrides set only qobuz, tidal, deezer and soundcloud, so
  `rip -q 4 url <beatport-url>` was a silent no-op even though
  qualityForSource reads Yandex and Beatport. All six are set, with the
  per-source floor applied and reported rather than silently ignored.

config: validation and a fixed reset
  Load checked nothing but misc.version, so a negative max_connections or a
  bogus conversion codec was accepted and only surfaced mid-rip. Adds
  Validate() covering per-source quality ranges, max_connections,
  requests_per_minute and truncate_to, and normalizes the conversion codec
  from the file through the same path as --codec. `config reset` assigned one
  value to both Config.File and Config.Session, so their Secrets slices shared
  a backing array; it now takes separate copies.

  Tests cover the shipped defaults and config.toml.example, which is how the
  over-strict artwork max-width bound in the first draft was caught: -1 is the
  documented "do not downscale" sentinel.

soundcloud: use the shared HTTP client
  It was the only provider constructing its own http.Client, so it silently
  ignored downloads.verify_ssl and max_connections and bypassed the transport
  that redacts credentials from -vv logs. It also had no rate limiter at all.

qobuz: mobile fallback could not download a long track
  http.Client.Timeout bounds the whole request including the body read, so the
  30s API client aborted any track that took longer than 30s to stream. The
  body copy now uses a no-timeout client, as internal/download already does.

qobuz: HKDF no longer fails silently
  hexDecodeOrNil discarded its error, so a non-hex app secret keyed HKDF on
  nil, derived a wrong KEK and produced silently corrupt audio instead of an
  error.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-10-03 16:58:59 +02:00

258 lines
6.6 KiB
Go

package main
import (
"fmt"
"os"
"strconv"
"strings"
"streamrip-go/internal/config"
)
type smokeOptions struct {
qualitySet bool
quality int
ignoreDB bool
}
type globalOptions struct {
configPath string
folder string
noDB bool
qualitySet bool
quality int
codecSet bool
codec string
noProgress bool
noSSLVerify bool
verbose int
help bool
command string
commandArgs []string
}
func parseGlobalArgs(args []string) (globalOptions, error) {
opts := globalOptions{}
for i := 0; i < len(args); i++ {
arg := args[i]
if arg == "" {
continue
}
if !strings.HasPrefix(arg, "-") {
opts.command = arg
if i+1 < len(args) {
opts.commandArgs = append([]string(nil), args[i+1:]...)
}
return opts, nil
}
switch {
case isHelpArg(arg):
opts.help = true
return opts, nil
case arg == "-ndb" || arg == "--no-db":
opts.noDB = true
case arg == "--no-progress":
opts.noProgress = true
case arg == "--no-ssl-verify":
opts.noSSLVerify = true
case arg == "-v" || arg == "--verbose":
if opts.verbose < 2 {
opts.verbose++
}
case arg == "-vv":
if opts.verbose < 2 {
opts.verbose = 2
}
case arg == "-f" || arg == "--folder":
if i+1 >= len(args) {
return globalOptions{}, fmt.Errorf("%s requires a value", arg)
}
opts.folder = strings.TrimSpace(args[i+1])
i++
case strings.HasPrefix(arg, "--folder="):
opts.folder = strings.TrimSpace(strings.TrimPrefix(arg, "--folder="))
case arg == "--config-path":
if i+1 >= len(args) {
return globalOptions{}, fmt.Errorf("--config-path requires a value")
}
opts.configPath = strings.TrimSpace(args[i+1])
i++
case strings.HasPrefix(arg, "--config-path="):
opts.configPath = strings.TrimSpace(strings.TrimPrefix(arg, "--config-path="))
case arg == "-q" || arg == "--quality":
if i+1 >= len(args) {
return globalOptions{}, fmt.Errorf("%s requires a value", arg)
}
q, err := strconv.Atoi(args[i+1])
if err != nil || q < 0 || q > 4 {
return globalOptions{}, fmt.Errorf("invalid quality %q (expected 0-4)", args[i+1])
}
opts.qualitySet = true
opts.quality = q
i++
case strings.HasPrefix(arg, "--quality="):
qRaw := strings.TrimSpace(strings.TrimPrefix(arg, "--quality="))
q, err := strconv.Atoi(qRaw)
if err != nil || q < 0 || q > 4 {
return globalOptions{}, fmt.Errorf("invalid quality %q (expected 0-4)", qRaw)
}
opts.qualitySet = true
opts.quality = q
case arg == "-c" || arg == "--codec":
if i+1 >= len(args) {
return globalOptions{}, fmt.Errorf("%s requires a value", arg)
}
codec, err := normalizeCodec(args[i+1])
if err != nil {
return globalOptions{}, err
}
opts.codecSet = true
opts.codec = codec
i++
case strings.HasPrefix(arg, "--codec="):
codecRaw := strings.TrimSpace(strings.TrimPrefix(arg, "--codec="))
codec, err := normalizeCodec(codecRaw)
if err != nil {
return globalOptions{}, err
}
opts.codecSet = true
opts.codec = codec
default:
return globalOptions{}, fmt.Errorf("unknown global option %q", arg)
}
}
return opts, nil
}
// normalizeCodec delegates to config so the --codec flag and a codec set in
// the config file are validated by the same rules.
func normalizeCodec(raw string) (string, error) {
return config.NormalizeCodec(raw)
}
func applyGlobalConfigOverrides(cfg *config.Config, opts globalOptions) {
if opts.folder != "" {
cfg.Session.Downloads.Folder = opts.folder
}
if opts.noDB {
cfg.Session.Database.DownloadsEnabled = false
}
if opts.qualitySet {
applyQualityOverride(cfg, opts.quality)
}
if opts.codecSet {
cfg.Session.Conversion.Enabled = true
cfg.Session.Conversion.Codec = opts.codec
}
if opts.noProgress {
cfg.Session.CLI.ProgressBars = false
}
if opts.noSSLVerify {
cfg.Session.Downloads.VerifySSL = false
}
}
// minQualityForSource is the lowest quality id each source accepts. Qobuz and
// Beatport have no equivalent of the "lowest" tier that 0 means elsewhere.
var minQualityForSource = map[string]int{
"qobuz": 1,
"beatport": 1,
}
// applyQualityOverride applies a global -q/--quality to every source.
//
// It previously set only qobuz, tidal, deezer and soundcloud, so
// `rip -q 4 url <beatport-url>` was a silent no-op even though
// Main.qualityForSource reads Yandex and Beatport too. Sources with a higher
// floor are clamped rather than erroring, because one global flag has to work
// across a mixed queue.
func applyQualityOverride(cfg *config.Config, quality int) {
clamped := map[string]int{}
for _, source := range []string{"qobuz", "tidal", "deezer", "soundcloud", "yandex", "beatport"} {
q := quality
if min, ok := minQualityForSource[source]; ok && q < min {
q = min
clamped[source] = q
}
switch source {
case "qobuz":
cfg.Session.Qobuz.Quality = q
case "tidal":
cfg.Session.Tidal.Quality = q
case "deezer":
cfg.Session.Deezer.Quality = q
case "soundcloud":
cfg.Session.Soundcloud.Quality = q
case "yandex":
cfg.Session.Yandex.Quality = q
case "beatport":
cfg.Session.Beatport.Quality = q
}
}
for _, source := range []string{"qobuz", "beatport"} {
if q, ok := clamped[source]; ok {
fmt.Fprintf(os.Stderr, "note: %s has no quality %d; using %d for %s\n", source, quality, q, source)
}
}
}
func errorWithActionableHint(err error, opts globalOptions) string {
if err == nil {
return ""
}
msg := err.Error()
if opts.noSSLVerify {
return msg
}
lower := strings.ToLower(msg)
if strings.Contains(lower, "x509") || strings.Contains(lower, "certificate") || strings.Contains(lower, "tls") || strings.Contains(lower, "ssl") {
return msg + " (hint: try again with --no-ssl-verify)"
}
return msg
}
func parseSmokeOptions(args []string, minQuality int, maxQuality int) (smokeOptions, error) {
opts := smokeOptions{}
for _, arg := range args {
switch arg {
case "--force", "--ignore-db":
opts.ignoreDB = true
default:
q, err := parseQuality(arg, minQuality, maxQuality)
if err != nil {
return smokeOptions{}, fmt.Errorf("unknown option %q", arg)
}
opts.quality = q
opts.qualitySet = true
}
}
return opts, nil
}
func parseQuality(raw string, min int, max int) (int, error) {
q, err := strconv.Atoi(raw)
if err != nil {
return 0, err
}
if q < min || q > max {
return 0, fmt.Errorf("quality must be %d-%d, got %d", min, max, q)
}
return q, nil
}
func asString(v any) string {
switch t := v.(type) {
case string:
return t
case int:
return strconv.Itoa(t)
case int64:
return strconv.FormatInt(t, 10)
case float64:
return strconv.FormatFloat(t, 'f', -1, 64)
default:
return ""
}
}