mirror of
https://git.sr.ht/~joren/streamrip-go
synced 2026-07-08 08:16:13 +02:00
Compare commits
18 Commits
fix/qualit
...
fix/qobuz-
| Author | SHA1 | Date | |
|---|---|---|---|
|
59b476034e
|
|||
|
|
9618108f2a | ||
|
|
7a27845e75 | ||
|
|
945695cea7 | ||
| 9e27ba842f | |||
| 63e1f20e04 | |||
| 5a6d7926ff | |||
| a06e3fa996 | |||
|
b63889f559
|
|||
|
c29f5415ac
|
|||
| 6f6cca19b3 | |||
| 232901f3eb | |||
| d5b336ca4e | |||
| c1e89f5876 | |||
| 50ca5f564b | |||
| 6bc4b3b319 | |||
| d65dc182f8 | |||
| beb6ce6cbb |
211
cmd/rip/args.go
Normal file
211
cmd/rip/args.go
Normal file
@@ -0,0 +1,211 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"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 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 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":
|
||||||
|
opts.verbose = true
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
func normalizeCodec(raw string) (string, error) {
|
||||||
|
codec := strings.ToUpper(strings.TrimSpace(raw))
|
||||||
|
switch codec {
|
||||||
|
case "ALAC", "FLAC", "MP3", "AAC", "VORBIS":
|
||||||
|
return codec, nil
|
||||||
|
case "OGG":
|
||||||
|
return "VORBIS", nil
|
||||||
|
default:
|
||||||
|
return "", fmt.Errorf("unsupported codec %q (expected ALAC, FLAC, OGG, MP3, AAC)", 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 {
|
||||||
|
cfg.Session.Qobuz.Quality = opts.quality
|
||||||
|
cfg.Session.Tidal.Quality = opts.quality
|
||||||
|
cfg.Session.Deezer.Quality = opts.quality
|
||||||
|
cfg.Session.Soundcloud.Quality = 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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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 ""
|
||||||
|
}
|
||||||
|
}
|
||||||
234
cmd/rip/helpers.go
Normal file
234
cmd/rip/helpers.go
Normal file
@@ -0,0 +1,234 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"regexp"
|
||||||
|
"runtime"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"streamrip-go/internal/app"
|
||||||
|
"streamrip-go/internal/urlparse"
|
||||||
|
)
|
||||||
|
|
||||||
|
type fileIDItem struct {
|
||||||
|
Source string
|
||||||
|
MediaType string
|
||||||
|
ID string
|
||||||
|
}
|
||||||
|
|
||||||
|
type failedRow struct {
|
||||||
|
Source string
|
||||||
|
MediaType string
|
||||||
|
ID string
|
||||||
|
}
|
||||||
|
|
||||||
|
type lastFMOptions struct {
|
||||||
|
Source string
|
||||||
|
FallbackSource string
|
||||||
|
PlaylistURL string
|
||||||
|
}
|
||||||
|
|
||||||
|
type lastFMTrack struct {
|
||||||
|
Title string
|
||||||
|
Artist string
|
||||||
|
}
|
||||||
|
|
||||||
|
type resolvedLastFMTrack struct {
|
||||||
|
Source string
|
||||||
|
ID string
|
||||||
|
Query string
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
lastFMTitleTagsRe = regexp.MustCompile(`<a\b[^>]*\btitle=(?:"([^"]+)"|'([^']+)')`)
|
||||||
|
lastFMDataTrackArtistRe = regexp.MustCompile(`data-track-name=(?:"([^"]+)"|'([^']+)')[^>]*data-artist-name=(?:"([^"]+)"|'([^']+)')`)
|
||||||
|
lastFMTotalTracksRe = regexp.MustCompile(`data-playlisting-entry-count="(\d+)"`)
|
||||||
|
lastFMPlaylistTitleRe = regexp.MustCompile(`<h1[^>]*class="[^"]*playlisting-playlist-header-title[^"]*"[^>]*>([^<]+)</h1>`)
|
||||||
|
lastFMMirrorTitleRe = regexp.MustCompile(`^Title:\s*(.+?)\s+\|`)
|
||||||
|
lastFMMirrorLinkTextRe = regexp.MustCompile(`\[([^\]]+)\]\(`)
|
||||||
|
errLastFMInvalidSource = "unsupported source"
|
||||||
|
)
|
||||||
|
|
||||||
|
func addURLToQueue(ctx context.Context, mainApp *app.Main, raw string) bool {
|
||||||
|
parsed := urlparse.Parse(raw)
|
||||||
|
if parsed == nil {
|
||||||
|
fmt.Printf("invalid: %s\n", raw)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if parsed.Kind != urlparse.KindGeneric && parsed.Kind != urlparse.KindSoundcloud {
|
||||||
|
fmt.Printf("not yet supported: %s (kind=%s)\n", raw, parsed.Kind)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if parsed.Source != "qobuz" && parsed.Source != "tidal" && parsed.Source != "deezer" && parsed.Source != "soundcloud" {
|
||||||
|
fmt.Printf("provider not yet implemented: source=%s url=%s\n", parsed.Source, raw)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if err := mainApp.AddByID(ctx, parsed.Source, parsed.MediaType, parsed.ID); err != nil {
|
||||||
|
fmt.Printf("add failed: source=%s type=%s id=%s err=%v\n", parsed.Source, parsed.MediaType, parsed.ID, err)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseFileInput(content []byte) ([]fileIDItem, []string, int, bool, error) {
|
||||||
|
trimmed := strings.TrimSpace(string(content))
|
||||||
|
if trimmed == "" {
|
||||||
|
return nil, nil, 0, false, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var parsed any
|
||||||
|
if err := json.Unmarshal([]byte(trimmed), &parsed); err == nil {
|
||||||
|
arr, ok := parsed.([]any)
|
||||||
|
if !ok {
|
||||||
|
return nil, nil, 0, true, fmt.Errorf("json input must be an array of objects")
|
||||||
|
}
|
||||||
|
items := make([]fileIDItem, 0, len(arr))
|
||||||
|
for i, raw := range arr {
|
||||||
|
entry, ok := raw.(map[string]any)
|
||||||
|
if !ok {
|
||||||
|
return nil, nil, 0, true, fmt.Errorf("json item %d must be an object", i+1)
|
||||||
|
}
|
||||||
|
source := strings.ToLower(strings.TrimSpace(asString(entry["source"])))
|
||||||
|
mediaType := strings.ToLower(strings.TrimSpace(asString(entry["media_type"])))
|
||||||
|
if mediaType == "" {
|
||||||
|
mediaType = strings.ToLower(strings.TrimSpace(asString(entry["mediaType"])))
|
||||||
|
}
|
||||||
|
id := strings.TrimSpace(asString(entry["id"]))
|
||||||
|
if source == "" || mediaType == "" || id == "" {
|
||||||
|
return nil, nil, 0, true, fmt.Errorf("json item %d missing source/media_type/id", i+1)
|
||||||
|
}
|
||||||
|
items = append(items, fileIDItem{Source: source, MediaType: mediaType, ID: id})
|
||||||
|
}
|
||||||
|
return items, nil, 0, true, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
parts := strings.Fields(trimmed)
|
||||||
|
if len(parts) == 0 {
|
||||||
|
return nil, nil, 0, false, nil
|
||||||
|
}
|
||||||
|
seen := make(map[string]struct{}, len(parts))
|
||||||
|
urls := make([]string, 0, len(parts))
|
||||||
|
repeated := 0
|
||||||
|
for _, raw := range parts {
|
||||||
|
if _, ok := seen[raw]; ok {
|
||||||
|
repeated++
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
seen[raw] = struct{}{}
|
||||||
|
urls = append(urls, raw)
|
||||||
|
}
|
||||||
|
return nil, urls, repeated, false, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func promptYesNo(prompt string) (bool, error) {
|
||||||
|
reader := bufio.NewReader(os.Stdin)
|
||||||
|
fmt.Print(prompt)
|
||||||
|
line, err := reader.ReadString('\n')
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
line = strings.ToLower(strings.TrimSpace(line))
|
||||||
|
return line == "y" || line == "yes", nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func openConfigInEditor(path string, vim bool) error {
|
||||||
|
launch := func(name string, args ...string) error {
|
||||||
|
cmd := exec.Command(name, args...)
|
||||||
|
cmd.Stdin = os.Stdin
|
||||||
|
cmd.Stdout = os.Stdout
|
||||||
|
cmd.Stderr = os.Stderr
|
||||||
|
return cmd.Run()
|
||||||
|
}
|
||||||
|
|
||||||
|
if vim {
|
||||||
|
if p, err := exec.LookPath("nvim"); err == nil {
|
||||||
|
return launch(p, path)
|
||||||
|
}
|
||||||
|
if p, err := exec.LookPath("vim"); err == nil {
|
||||||
|
return launch(p, path)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if editor := strings.TrimSpace(os.Getenv("EDITOR")); editor != "" {
|
||||||
|
parts := strings.Fields(editor)
|
||||||
|
if len(parts) > 0 {
|
||||||
|
return launch(parts[0], append(parts[1:], path)...)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
switch runtime.GOOS {
|
||||||
|
case "darwin":
|
||||||
|
return launch("open", path)
|
||||||
|
case "windows":
|
||||||
|
return launch("cmd", "/c", "start", "", path)
|
||||||
|
default:
|
||||||
|
if p, err := exec.LookPath("xdg-open"); err == nil {
|
||||||
|
return launch(p, path)
|
||||||
|
}
|
||||||
|
return fmt.Errorf("could not find an editor (set $EDITOR or install xdg-open)")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func listDownloadsRows(path string) ([]string, error) {
|
||||||
|
db, err := sql.Open("sqlite", path)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer func() { _ = db.Close() }()
|
||||||
|
|
||||||
|
rows, err := db.Query(`SELECT id FROM downloads ORDER BY rowid`)
|
||||||
|
if err != nil {
|
||||||
|
if isNoSuchTableErr(err) {
|
||||||
|
return []string{}, nil
|
||||||
|
}
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer func() { _ = rows.Close() }()
|
||||||
|
|
||||||
|
out := []string{}
|
||||||
|
for rows.Next() {
|
||||||
|
var id string
|
||||||
|
if err = rows.Scan(&id); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
out = append(out, id)
|
||||||
|
}
|
||||||
|
return out, rows.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
func listFailedRows(path string) ([]failedRow, error) {
|
||||||
|
db, err := sql.Open("sqlite", path)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer func() { _ = db.Close() }()
|
||||||
|
|
||||||
|
rows, err := db.Query(`SELECT source, media_type, id FROM failed_downloads ORDER BY rowid`)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer func() { _ = rows.Close() }()
|
||||||
|
|
||||||
|
out := []failedRow{}
|
||||||
|
for rows.Next() {
|
||||||
|
var r failedRow
|
||||||
|
if err = rows.Scan(&r.Source, &r.MediaType, &r.ID); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
out = append(out, r)
|
||||||
|
}
|
||||||
|
return out, rows.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
func isNoSuchTableErr(err error) bool {
|
||||||
|
if err == nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return strings.Contains(strings.ToLower(err.Error()), "no such table")
|
||||||
|
}
|
||||||
430
cmd/rip/lastfm.go
Normal file
430
cmd/rip/lastfm.go
Normal file
@@ -0,0 +1,430 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"html"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"streamrip-go/internal/app"
|
||||||
|
"streamrip-go/internal/netutil"
|
||||||
|
"streamrip-go/internal/provider"
|
||||||
|
)
|
||||||
|
|
||||||
|
func parseLastFMArgs(args []string, defaultSource, defaultFallback string) (lastFMOptions, error) {
|
||||||
|
opts := lastFMOptions{Source: strings.ToLower(strings.TrimSpace(defaultSource)), FallbackSource: strings.ToLower(strings.TrimSpace(defaultFallback))}
|
||||||
|
for i := 0; i < len(args); i++ {
|
||||||
|
switch args[i] {
|
||||||
|
case "-s", "--source":
|
||||||
|
if i+1 >= len(args) {
|
||||||
|
return lastFMOptions{}, fmt.Errorf("--source requires a value")
|
||||||
|
}
|
||||||
|
opts.Source = strings.ToLower(strings.TrimSpace(args[i+1]))
|
||||||
|
i++
|
||||||
|
case "-fs", "--fallback-source":
|
||||||
|
if i+1 >= len(args) {
|
||||||
|
return lastFMOptions{}, fmt.Errorf("--fallback-source requires a value")
|
||||||
|
}
|
||||||
|
opts.FallbackSource = strings.ToLower(strings.TrimSpace(args[i+1]))
|
||||||
|
i++
|
||||||
|
default:
|
||||||
|
if strings.HasPrefix(args[i], "-") {
|
||||||
|
return lastFMOptions{}, fmt.Errorf("unknown option %q", args[i])
|
||||||
|
}
|
||||||
|
if opts.PlaylistURL != "" {
|
||||||
|
return lastFMOptions{}, fmt.Errorf("unexpected extra argument %q", args[i])
|
||||||
|
}
|
||||||
|
opts.PlaylistURL = strings.TrimSpace(args[i])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if opts.Source == "" {
|
||||||
|
opts.Source = "qobuz"
|
||||||
|
}
|
||||||
|
if opts.PlaylistURL == "" {
|
||||||
|
return lastFMOptions{}, fmt.Errorf("missing playlist url")
|
||||||
|
}
|
||||||
|
if !isValidLastFMPlaylistURL(opts.PlaylistURL) {
|
||||||
|
return lastFMOptions{}, fmt.Errorf("playlist url must be a last.fm url")
|
||||||
|
}
|
||||||
|
if !isAllowedSearchSource(opts.Source) {
|
||||||
|
return lastFMOptions{}, fmt.Errorf("%s %q", errLastFMInvalidSource, opts.Source)
|
||||||
|
}
|
||||||
|
if opts.FallbackSource != "" && !isAllowedSearchSource(opts.FallbackSource) {
|
||||||
|
return lastFMOptions{}, fmt.Errorf("%s %q", errLastFMInvalidSource, opts.FallbackSource)
|
||||||
|
}
|
||||||
|
return opts, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func isValidLastFMPlaylistURL(raw string) bool {
|
||||||
|
u, err := url.Parse(strings.TrimSpace(raw))
|
||||||
|
if err != nil || u == nil || u.Host == "" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
s := strings.ToLower(strings.TrimSpace(u.Scheme))
|
||||||
|
if s != "http" && s != "https" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
h := strings.ToLower(strings.TrimPrefix(strings.TrimSpace(u.Host), "www."))
|
||||||
|
if h != "last.fm" && !strings.HasSuffix(h, ".last.fm") {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
p := strings.ToLower(strings.TrimSpace(u.Path))
|
||||||
|
return strings.Contains(p, "/playlists/")
|
||||||
|
}
|
||||||
|
|
||||||
|
func fetchLastFMPlaylist(ctx context.Context, verifySSL bool, playlistURL string) (string, []lastFMTrack, error) {
|
||||||
|
parsed, err := url.Parse(playlistURL)
|
||||||
|
if err != nil || parsed.Scheme == "" || parsed.Host == "" {
|
||||||
|
return "", nil, fmt.Errorf("invalid playlist url")
|
||||||
|
}
|
||||||
|
if !isValidLastFMPlaylistURL(playlistURL) {
|
||||||
|
return "", nil, fmt.Errorf("invalid playlist url")
|
||||||
|
}
|
||||||
|
client := netutil.NewHTTPClient(30*time.Second, verifySSL, 0)
|
||||||
|
|
||||||
|
page1, err := fetchLastFMPlaylistPage(ctx, client, parsed, 1)
|
||||||
|
if err != nil {
|
||||||
|
return fetchLastFMPlaylistViaMirror(ctx, verifySSL, playlistURL)
|
||||||
|
}
|
||||||
|
title, total, err := extractLastFMPlaylistInfo(page1)
|
||||||
|
if err != nil {
|
||||||
|
return fetchLastFMPlaylistViaMirror(ctx, verifySSL, playlistURL)
|
||||||
|
}
|
||||||
|
tracks := extractLastFMTitleArtistPairs(page1)
|
||||||
|
if total <= len(tracks) || total <= 50 {
|
||||||
|
if len(tracks) > total && total > 0 {
|
||||||
|
tracks = tracks[:total]
|
||||||
|
}
|
||||||
|
return title, tracks, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
remaining := total - 50
|
||||||
|
lastPage := 1 + remaining/50
|
||||||
|
if remaining%50 != 0 {
|
||||||
|
lastPage++
|
||||||
|
}
|
||||||
|
for page := 2; page <= lastPage; page++ {
|
||||||
|
body, fetchErr := fetchLastFMPlaylistPage(ctx, client, parsed, page)
|
||||||
|
if fetchErr != nil {
|
||||||
|
return "", nil, fetchErr
|
||||||
|
}
|
||||||
|
tracks = append(tracks, extractLastFMTitleArtistPairs(body)...)
|
||||||
|
}
|
||||||
|
if len(tracks) > total {
|
||||||
|
tracks = tracks[:total]
|
||||||
|
}
|
||||||
|
return title, tracks, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func fetchLastFMPlaylistViaMirror(ctx context.Context, verifySSL bool, playlistURL string) (string, []lastFMTrack, error) {
|
||||||
|
client := netutil.NewHTTPClient(30*time.Second, verifySSL, 0)
|
||||||
|
all := make([]lastFMTrack, 0, 200)
|
||||||
|
title := ""
|
||||||
|
|
||||||
|
for page := 1; page <= 50; page++ {
|
||||||
|
body, err := fetchLastFMPlaylistMirrorPage(ctx, client, playlistURL, page)
|
||||||
|
if err != nil {
|
||||||
|
if page == 1 {
|
||||||
|
return "", nil, err
|
||||||
|
}
|
||||||
|
break
|
||||||
|
}
|
||||||
|
pageTitle, tracks := extractLastFMTracksFromMirrorMarkdown(body)
|
||||||
|
if title == "" && strings.TrimSpace(pageTitle) != "" {
|
||||||
|
title = pageTitle
|
||||||
|
}
|
||||||
|
if len(tracks) == 0 {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
all = append(all, tracks...)
|
||||||
|
if !strings.Contains(strings.ToLower(body), "show more") {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(all) == 0 {
|
||||||
|
return "", nil, fmt.Errorf("could not parse playlist tracks from last.fm")
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(title) == "" {
|
||||||
|
title = "Last.fm Playlist"
|
||||||
|
}
|
||||||
|
return title, all, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func fetchLastFMPlaylistMirrorPage(ctx context.Context, client *http.Client, playlistURL string, page int) (string, error) {
|
||||||
|
u, err := url.Parse(playlistURL)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if page > 1 {
|
||||||
|
q := u.Query()
|
||||||
|
q.Set("page", strconv.Itoa(page))
|
||||||
|
u.RawQuery = q.Encode()
|
||||||
|
}
|
||||||
|
raw := u.String()
|
||||||
|
raw = strings.TrimPrefix(raw, "https://")
|
||||||
|
raw = strings.TrimPrefix(raw, "http://")
|
||||||
|
mirrorURL := "https://r.jina.ai/http://" + raw
|
||||||
|
|
||||||
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, mirrorURL, nil)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
req.Header.Set("User-Agent", "streamrip-go/0")
|
||||||
|
resp, err := client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
defer func() { _ = resp.Body.Close() }()
|
||||||
|
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||||
|
return "", fmt.Errorf("lastfm mirror request failed: status %d", resp.StatusCode)
|
||||||
|
}
|
||||||
|
b, err := io.ReadAll(resp.Body)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return string(b), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func fetchLastFMPlaylistPage(ctx context.Context, client *http.Client, parsed *url.URL, page int) (string, error) {
|
||||||
|
u := *parsed
|
||||||
|
if page > 1 {
|
||||||
|
q := u.Query()
|
||||||
|
q.Set("page", strconv.Itoa(page))
|
||||||
|
u.RawQuery = q.Encode()
|
||||||
|
}
|
||||||
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
req.Header.Set("User-Agent", "streamrip-go/0")
|
||||||
|
|
||||||
|
resp, err := client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
defer func() { _ = resp.Body.Close() }()
|
||||||
|
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||||
|
return "", fmt.Errorf("lastfm request failed: status %d", resp.StatusCode)
|
||||||
|
}
|
||||||
|
b, err := io.ReadAll(resp.Body)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return string(b), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func extractLastFMPlaylistInfo(page string) (string, int, error) {
|
||||||
|
titleMatch := lastFMPlaylistTitleRe.FindStringSubmatch(page)
|
||||||
|
if len(titleMatch) < 2 {
|
||||||
|
return "", 0, fmt.Errorf("could not parse playlist title")
|
||||||
|
}
|
||||||
|
totalMatch := lastFMTotalTracksRe.FindStringSubmatch(page)
|
||||||
|
if len(totalMatch) < 2 {
|
||||||
|
return "", 0, fmt.Errorf("could not parse total track count")
|
||||||
|
}
|
||||||
|
total, err := strconv.Atoi(totalMatch[1])
|
||||||
|
if err != nil {
|
||||||
|
return "", 0, fmt.Errorf("invalid total track count")
|
||||||
|
}
|
||||||
|
return html.UnescapeString(strings.TrimSpace(titleMatch[1])), total, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func extractLastFMTitleArtistPairs(page string) []lastFMTrack {
|
||||||
|
dataPairs := lastFMDataTrackArtistRe.FindAllStringSubmatch(page, -1)
|
||||||
|
if len(dataPairs) > 0 {
|
||||||
|
out := make([]lastFMTrack, 0, len(dataPairs))
|
||||||
|
for _, m := range dataPairs {
|
||||||
|
title := html.UnescapeString(strings.TrimSpace(firstNonEmpty(m[1], m[2])))
|
||||||
|
artist := html.UnescapeString(strings.TrimSpace(firstNonEmpty(m[3], m[4])))
|
||||||
|
if title == "" || artist == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
out = append(out, lastFMTrack{Title: title, Artist: artist})
|
||||||
|
}
|
||||||
|
if len(out) > 0 {
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
titles := lastFMTitleTagsRe.FindAllStringSubmatch(page, -1)
|
||||||
|
out := make([]lastFMTrack, 0, len(titles)/2)
|
||||||
|
for i := 0; i+1 < len(titles); i += 2 {
|
||||||
|
titleRaw := strings.TrimSpace(firstNonEmpty(titles[i][1], titles[i][2]))
|
||||||
|
artistRaw := strings.TrimSpace(firstNonEmpty(titles[i+1][1], titles[i+1][2]))
|
||||||
|
if strings.EqualFold(titleRaw, "Play on YouTube") || strings.EqualFold(artistRaw, "Play on YouTube") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
title := html.UnescapeString(titleRaw)
|
||||||
|
artist := html.UnescapeString(artistRaw)
|
||||||
|
if title == "" || artist == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
out = append(out, lastFMTrack{Title: title, Artist: artist})
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func firstNonEmpty(items ...string) string {
|
||||||
|
for _, item := range items {
|
||||||
|
if strings.TrimSpace(item) != "" {
|
||||||
|
return strings.TrimSpace(item)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func extractLastFMTracksFromMirrorMarkdown(md string) (string, []lastFMTrack) {
|
||||||
|
lines := strings.Split(strings.ReplaceAll(md, "\r\n", "\n"), "\n")
|
||||||
|
title := ""
|
||||||
|
tracks := make([]lastFMTrack, 0, 100)
|
||||||
|
for _, line := range lines {
|
||||||
|
line = strings.TrimSpace(line)
|
||||||
|
if title == "" {
|
||||||
|
if m := lastFMMirrorTitleRe.FindStringSubmatch(line); len(m) >= 2 {
|
||||||
|
title = strings.TrimSpace(html.UnescapeString(m[1]))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !strings.HasPrefix(line, "|") || !strings.Contains(strings.ToLower(line), "play track") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
cols := splitMarkdownTableRow(line)
|
||||||
|
if len(cols) < 6 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
trackName := markdownLinkText(cols[3])
|
||||||
|
artist := markdownLinkText(cols[4])
|
||||||
|
if strings.TrimSpace(trackName) == "" || strings.TrimSpace(artist) == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
tracks = append(tracks, lastFMTrack{Title: html.UnescapeString(strings.TrimSpace(trackName)), Artist: html.UnescapeString(strings.TrimSpace(artist))})
|
||||||
|
}
|
||||||
|
return title, tracks
|
||||||
|
}
|
||||||
|
|
||||||
|
func splitMarkdownTableRow(line string) []string {
|
||||||
|
trimmed := strings.TrimSpace(line)
|
||||||
|
trimmed = strings.TrimPrefix(trimmed, "|")
|
||||||
|
trimmed = strings.TrimSuffix(trimmed, "|")
|
||||||
|
parts := strings.Split(trimmed, "|")
|
||||||
|
out := make([]string, 0, len(parts))
|
||||||
|
for _, p := range parts {
|
||||||
|
out = append(out, strings.TrimSpace(p))
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func markdownLinkText(cell string) string {
|
||||||
|
m := lastFMMirrorLinkTextRe.FindStringSubmatch(cell)
|
||||||
|
if len(m) >= 2 {
|
||||||
|
return m[1]
|
||||||
|
}
|
||||||
|
return strings.TrimSpace(cell)
|
||||||
|
}
|
||||||
|
|
||||||
|
func resolveLastFMTracks(ctx context.Context, mainApp *app.Main, opts lastFMOptions, tracks []lastFMTrack) ([]resolvedLastFMTrack, error) {
|
||||||
|
primary, err := mainApp.GetLoggedInProvider(ctx, opts.Source)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s login error: %w", opts.Source, err)
|
||||||
|
}
|
||||||
|
var fallback provider.Client
|
||||||
|
if opts.FallbackSource != "" && opts.FallbackSource != opts.Source {
|
||||||
|
fallback, err = mainApp.GetLoggedInProvider(ctx, opts.FallbackSource)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s login error: %w", opts.FallbackSource, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
found := 0
|
||||||
|
failed := 0
|
||||||
|
resolved := make([]resolvedLastFMTrack, 0, len(tracks))
|
||||||
|
for i, tr := range tracks {
|
||||||
|
query := strings.TrimSpace(tr.Title + " " + tr.Artist)
|
||||||
|
id, source, searchErr := searchLastFMTrack(ctx, opts, primary, fallback, query)
|
||||||
|
if searchErr != nil {
|
||||||
|
failed++
|
||||||
|
fmt.Printf("[%d/%d] search failed: %s (%v)\n", i+1, len(tracks), query, searchErr)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if id == "" {
|
||||||
|
failed++
|
||||||
|
fmt.Printf("[%d/%d] no result: %s\n", i+1, len(tracks), query)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
resolved = append(resolved, resolvedLastFMTrack{Source: source, ID: id, Query: query})
|
||||||
|
found++
|
||||||
|
fmt.Printf("[%d/%d] found: %s (%s)\n", i+1, len(tracks), query, source)
|
||||||
|
}
|
||||||
|
fmt.Printf("lastfm resolve complete: %d found, %d failed\n", found, failed)
|
||||||
|
return resolved, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func fetchSoundcloudOEmbed(ctx context.Context, verifySSL bool, trackURL string) (map[string]any, error) {
|
||||||
|
parsed, err := url.Parse(trackURL)
|
||||||
|
if err != nil || parsed.Scheme == "" || parsed.Host == "" {
|
||||||
|
return nil, fmt.Errorf("invalid soundcloud url")
|
||||||
|
}
|
||||||
|
|
||||||
|
q := url.Values{}
|
||||||
|
q.Set("format", "json")
|
||||||
|
q.Set("url", trackURL)
|
||||||
|
endpoint := "https://soundcloud.com/oembed?" + q.Encode()
|
||||||
|
|
||||||
|
client := netutil.NewHTTPClient(20*time.Second, verifySSL, 0)
|
||||||
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
req.Header.Set("User-Agent", "streamrip-go/0.1")
|
||||||
|
|
||||||
|
resp, err := client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer func() { _ = resp.Body.Close() }()
|
||||||
|
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||||
|
return nil, fmt.Errorf("soundcloud oembed failed: status %d", resp.StatusCode)
|
||||||
|
}
|
||||||
|
body, err := io.ReadAll(resp.Body)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
out := map[string]any{}
|
||||||
|
if err = json.Unmarshal(body, &out); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func searchLastFMTrack(ctx context.Context, opts lastFMOptions, primary provider.Client, fallback provider.Client, query string) (string, string, error) {
|
||||||
|
pages, err := primary.Search(ctx, "track", query, 1)
|
||||||
|
if err == nil {
|
||||||
|
results := normalizeSearchResults(opts.Source, "track", pages)
|
||||||
|
if len(results) > 0 {
|
||||||
|
return results[0].ID, opts.Source, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if fallback != nil {
|
||||||
|
pages, fbErr := fallback.Search(ctx, "track", query, 1)
|
||||||
|
if fbErr != nil {
|
||||||
|
if err != nil {
|
||||||
|
return "", "", fmt.Errorf("primary=%v fallback=%v", err, fbErr)
|
||||||
|
}
|
||||||
|
return "", "", fbErr
|
||||||
|
}
|
||||||
|
results := normalizeSearchResults(opts.FallbackSource, "track", pages)
|
||||||
|
if len(results) > 0 {
|
||||||
|
return results[0].ID, opts.FallbackSource, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return "", "", err
|
||||||
|
}
|
||||||
|
return "", "", nil
|
||||||
|
}
|
||||||
1364
cmd/rip/main.go
1364
cmd/rip/main.go
File diff suppressed because it is too large
Load Diff
667
cmd/rip/search.go
Normal file
667
cmd/rip/search.go
Normal file
@@ -0,0 +1,667 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/AlecAivazis/survey/v2"
|
||||||
|
|
||||||
|
"streamrip-go/internal/jsonutil"
|
||||||
|
)
|
||||||
|
|
||||||
|
type searchResult struct {
|
||||||
|
ID string
|
||||||
|
Title string
|
||||||
|
Artist string
|
||||||
|
Album string
|
||||||
|
Date string
|
||||||
|
Releases int
|
||||||
|
TrackCount int
|
||||||
|
Explicit bool
|
||||||
|
}
|
||||||
|
|
||||||
|
type searchOptions struct {
|
||||||
|
query string
|
||||||
|
limit int
|
||||||
|
ignoreDB bool
|
||||||
|
noDownload bool
|
||||||
|
first bool
|
||||||
|
outputFile string
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseSearchArgs(args []string, defaultLimit int) (searchOptions, error) {
|
||||||
|
if defaultLimit <= 0 {
|
||||||
|
defaultLimit = 20
|
||||||
|
}
|
||||||
|
limit := defaultLimit
|
||||||
|
parts := make([]string, 0, len(args))
|
||||||
|
ignoreDB := false
|
||||||
|
noDownload := false
|
||||||
|
first := false
|
||||||
|
outputFile := ""
|
||||||
|
for i := 0; i < len(args); i++ {
|
||||||
|
if args[i] == "--" {
|
||||||
|
if i+1 < len(args) {
|
||||||
|
parts = append(parts, args[i+1:]...)
|
||||||
|
}
|
||||||
|
break
|
||||||
|
}
|
||||||
|
switch args[i] {
|
||||||
|
case "--force", "--ignore-db":
|
||||||
|
ignoreDB = true
|
||||||
|
continue
|
||||||
|
case "--no-download":
|
||||||
|
noDownload = true
|
||||||
|
continue
|
||||||
|
case "--first":
|
||||||
|
first = true
|
||||||
|
continue
|
||||||
|
case "--output-file":
|
||||||
|
if i+1 >= len(args) {
|
||||||
|
return searchOptions{}, fmt.Errorf("--output-file requires a path")
|
||||||
|
}
|
||||||
|
outputFile = strings.TrimSpace(args[i+1])
|
||||||
|
if outputFile == "" {
|
||||||
|
return searchOptions{}, fmt.Errorf("--output-file requires a non-empty path")
|
||||||
|
}
|
||||||
|
i++
|
||||||
|
continue
|
||||||
|
case "--num-results":
|
||||||
|
if i+1 >= len(args) {
|
||||||
|
return searchOptions{}, fmt.Errorf("--num-results requires a value")
|
||||||
|
}
|
||||||
|
v, err := strconv.Atoi(args[i+1])
|
||||||
|
if err != nil || v <= 0 {
|
||||||
|
return searchOptions{}, fmt.Errorf("invalid --num-results value %q", args[i+1])
|
||||||
|
}
|
||||||
|
limit = v
|
||||||
|
i++
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if args[i] == "--limit" {
|
||||||
|
if i+1 >= len(args) {
|
||||||
|
return searchOptions{}, fmt.Errorf("--limit requires a value")
|
||||||
|
}
|
||||||
|
v, err := strconv.Atoi(args[i+1])
|
||||||
|
if err != nil || v <= 0 {
|
||||||
|
return searchOptions{}, fmt.Errorf("invalid --limit value %q", args[i+1])
|
||||||
|
}
|
||||||
|
limit = v
|
||||||
|
i++
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if strings.HasPrefix(args[i], "-") {
|
||||||
|
return searchOptions{}, fmt.Errorf("unknown option %q", args[i])
|
||||||
|
}
|
||||||
|
parts = append(parts, args[i])
|
||||||
|
}
|
||||||
|
return searchOptions{
|
||||||
|
query: strings.TrimSpace(strings.Join(parts, " ")),
|
||||||
|
limit: limit,
|
||||||
|
ignoreDB: ignoreDB,
|
||||||
|
noDownload: noDownload,
|
||||||
|
first: first,
|
||||||
|
outputFile: outputFile,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func promptSearchSelection(results []searchResult) ([]int, error) {
|
||||||
|
reader := bufio.NewReader(os.Stdin)
|
||||||
|
for {
|
||||||
|
fmt.Print("Select results to download (e.g. 1,3-5; a=all; q=cancel): ")
|
||||||
|
line, err := reader.ReadString('\n')
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
line = strings.TrimSpace(line)
|
||||||
|
if line == "" || strings.EqualFold(line, "q") || strings.EqualFold(line, "quit") {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
if strings.EqualFold(line, "a") || strings.EqualFold(line, "all") {
|
||||||
|
out := make([]int, 0, len(results))
|
||||||
|
for i := range results {
|
||||||
|
out = append(out, i)
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
selected := map[int]struct{}{}
|
||||||
|
chunks := strings.Split(line, ",")
|
||||||
|
ok := true
|
||||||
|
for _, raw := range chunks {
|
||||||
|
part := strings.TrimSpace(raw)
|
||||||
|
if part == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if strings.Contains(part, "-") {
|
||||||
|
bounds := strings.SplitN(part, "-", 2)
|
||||||
|
if len(bounds) != 2 {
|
||||||
|
ok = false
|
||||||
|
break
|
||||||
|
}
|
||||||
|
start, err1 := strconv.Atoi(strings.TrimSpace(bounds[0]))
|
||||||
|
end, err2 := strconv.Atoi(strings.TrimSpace(bounds[1]))
|
||||||
|
if err1 != nil || err2 != nil || start <= 0 || end <= 0 || start > end {
|
||||||
|
ok = false
|
||||||
|
break
|
||||||
|
}
|
||||||
|
for i := start; i <= end; i++ {
|
||||||
|
if i > len(results) {
|
||||||
|
ok = false
|
||||||
|
break
|
||||||
|
}
|
||||||
|
selected[i-1] = struct{}{}
|
||||||
|
}
|
||||||
|
if !ok {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
idx, err := strconv.Atoi(part)
|
||||||
|
if err != nil || idx <= 0 || idx > len(results) {
|
||||||
|
ok = false
|
||||||
|
break
|
||||||
|
}
|
||||||
|
selected[idx-1] = struct{}{}
|
||||||
|
}
|
||||||
|
|
||||||
|
if !ok || len(selected) == 0 {
|
||||||
|
fmt.Println("Invalid selection, try again.")
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
out := make([]int, 0, len(selected))
|
||||||
|
for idx := range selected {
|
||||||
|
out = append(out, idx)
|
||||||
|
}
|
||||||
|
for i := 1; i < len(out); i++ {
|
||||||
|
for j := i; j > 0 && out[j] < out[j-1]; j-- {
|
||||||
|
out[j], out[j-1] = out[j-1], out[j]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func promptSearchSelectionMenu(source, mediaType, query string, results []searchResult) ([]int, error) {
|
||||||
|
if len(results) == 0 {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
prevTemplate := survey.MultiSelectQuestionTemplate
|
||||||
|
survey.MultiSelectQuestionTemplate = streamripLikeSearchTemplate
|
||||||
|
defer func() {
|
||||||
|
survey.MultiSelectQuestionTemplate = prevTemplate
|
||||||
|
}()
|
||||||
|
|
||||||
|
labels := make([]string, 0, len(results))
|
||||||
|
labelToIndex := map[string]int{}
|
||||||
|
for i, r := range results {
|
||||||
|
label := formatSearchOptionLabel(i+1, mediaType, r)
|
||||||
|
labels = append(labels, label)
|
||||||
|
labelToIndex[label] = i
|
||||||
|
}
|
||||||
|
pageSize := len(labels)
|
||||||
|
if pageSize < 15 {
|
||||||
|
pageSize = 15
|
||||||
|
}
|
||||||
|
if pageSize > 30 {
|
||||||
|
pageSize = 30
|
||||||
|
}
|
||||||
|
|
||||||
|
selected := []string{}
|
||||||
|
prompt := &survey.MultiSelect{
|
||||||
|
Message: fmt.Sprintf("Results for %s '%s' from %s", mediaType, query, jsonutil.TitleCase(source)),
|
||||||
|
Help: "SPACE - select, ENTER - download, ESC - exit",
|
||||||
|
Options: labels,
|
||||||
|
Description: func(value string, index int) string {
|
||||||
|
resultIndex, ok := labelToIndex[value]
|
||||||
|
if !ok || resultIndex < 0 || resultIndex >= len(results) {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return formatSearchDetails(mediaType, results[resultIndex])
|
||||||
|
},
|
||||||
|
PageSize: pageSize,
|
||||||
|
}
|
||||||
|
if err := survey.AskOne(prompt, &selected); err != nil {
|
||||||
|
if strings.Contains(strings.ToLower(err.Error()), "interrupt") {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(selected) == 0 {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
out := make([]int, 0, len(selected))
|
||||||
|
for _, label := range selected {
|
||||||
|
if idx, ok := labelToIndex[label]; ok {
|
||||||
|
out = append(out, idx)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for i := 1; i < len(out); i++ {
|
||||||
|
for j := i; j > 0 && out[j] < out[j-1]; j-- {
|
||||||
|
out[j], out[j-1] = out[j-1], out[j]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
const streamripLikeSearchTemplate = `
|
||||||
|
{{ color "default+hb"}}{{ .Message }}{{color "reset"}}
|
||||||
|
{{- if .Help }}
|
||||||
|
{{ .Help }}
|
||||||
|
{{- end }}
|
||||||
|
{{- range $ix, $option := .PageEntries }}
|
||||||
|
{{ if eq $.SelectedIndex $ix }}>{{ else }} {{ end }} [{{ if index $.Checked $option.Index }}x{{ else }} {{ end }}] {{ $option.Value }}
|
||||||
|
{{- end }}
|
||||||
|
|
||||||
|
preview
|
||||||
|
{{- if gt (len .PageEntries) 0 }}
|
||||||
|
{{ $current := index .PageEntries .SelectedIndex }}
|
||||||
|
{{ $.GetDescription $current }}
|
||||||
|
{{- end }}
|
||||||
|
`
|
||||||
|
|
||||||
|
func writeSearchResultsToFile(source, mediaType string, results []searchResult, path string) error {
|
||||||
|
type outItem struct {
|
||||||
|
Source string `json:"source"`
|
||||||
|
MediaType string `json:"media_type"`
|
||||||
|
ID string `json:"id"`
|
||||||
|
Title string `json:"title"`
|
||||||
|
}
|
||||||
|
out := make([]outItem, 0, len(results))
|
||||||
|
for _, r := range results {
|
||||||
|
out = append(out, outItem{Source: source, MediaType: mediaType, ID: r.ID, Title: r.Title})
|
||||||
|
}
|
||||||
|
b, err := json.MarshalIndent(out, "", " ")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
dir := filepath.Dir(path)
|
||||||
|
if dir != "" && dir != "." {
|
||||||
|
if err = os.MkdirAll(dir, 0o755); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return os.WriteFile(path, b, 0o644)
|
||||||
|
}
|
||||||
|
|
||||||
|
func isAllowedSearchSource(source string) bool {
|
||||||
|
return source == "qobuz" || source == "tidal" || source == "deezer" || source == "soundcloud"
|
||||||
|
}
|
||||||
|
|
||||||
|
func isAllowedMediaType(mediaType string) bool {
|
||||||
|
switch mediaType {
|
||||||
|
case "track", "album", "playlist", "artist", "label", "video":
|
||||||
|
return true
|
||||||
|
default:
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func promptSearchInteractive(defaultLimit int) (string, string, searchOptions, error) {
|
||||||
|
reader := bufio.NewReader(os.Stdin)
|
||||||
|
|
||||||
|
read := func(prompt string) (string, error) {
|
||||||
|
fmt.Print(prompt)
|
||||||
|
line, err := reader.ReadString('\n')
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return strings.TrimSpace(line), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
for {
|
||||||
|
source, err := read("Source [qobuz/tidal/deezer/soundcloud]: ")
|
||||||
|
if err != nil {
|
||||||
|
return "", "", searchOptions{}, err
|
||||||
|
}
|
||||||
|
source = strings.ToLower(source)
|
||||||
|
if !isAllowedSearchSource(source) {
|
||||||
|
fmt.Println("Invalid source.")
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
mediaType, err := read("Type [track/album/playlist/artist/label/video]: ")
|
||||||
|
if err != nil {
|
||||||
|
return "", "", searchOptions{}, err
|
||||||
|
}
|
||||||
|
mediaType = strings.ToLower(mediaType)
|
||||||
|
if !isAllowedMediaType(mediaType) {
|
||||||
|
fmt.Println("Invalid media type.")
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if source == "soundcloud" && mediaType != "track" && mediaType != "playlist" {
|
||||||
|
fmt.Println("SoundCloud search supports track and playlist only.")
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
query, err := read("Query: ")
|
||||||
|
if err != nil {
|
||||||
|
return "", "", searchOptions{}, err
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(query) == "" {
|
||||||
|
fmt.Println("Query cannot be empty.")
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
limitRaw, err := read(fmt.Sprintf("Limit [%d]: ", defaultLimit))
|
||||||
|
if err != nil {
|
||||||
|
return "", "", searchOptions{}, err
|
||||||
|
}
|
||||||
|
limit := defaultLimit
|
||||||
|
if strings.TrimSpace(limitRaw) != "" {
|
||||||
|
v, convErr := strconv.Atoi(limitRaw)
|
||||||
|
if convErr != nil || v <= 0 {
|
||||||
|
fmt.Println("Invalid limit.")
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
limit = v
|
||||||
|
}
|
||||||
|
|
||||||
|
return source, mediaType, searchOptions{query: query, limit: limit}, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func normalizeSearchResults(source, mediaType string, pages []map[string]any) []searchResult {
|
||||||
|
results := make([]searchResult, 0)
|
||||||
|
seen := map[string]struct{}{}
|
||||||
|
appendUnique := func(r searchResult) {
|
||||||
|
if strings.TrimSpace(r.ID) == "" || strings.TrimSpace(r.Title) == "" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
key := r.ID
|
||||||
|
if _, ok := seen[key]; ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
seen[key] = struct{}{}
|
||||||
|
results = append(results, r)
|
||||||
|
}
|
||||||
|
for _, page := range pages {
|
||||||
|
switch source {
|
||||||
|
case "qobuz":
|
||||||
|
key := mediaType + "s"
|
||||||
|
bucket, ok := page[key].(map[string]any)
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
items, ok := bucket["items"].([]any)
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, raw := range items {
|
||||||
|
itm, ok := raw.(map[string]any)
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
id := asString(itm["id"])
|
||||||
|
title := asString(itm["title"])
|
||||||
|
if title == "" {
|
||||||
|
title = asString(itm["name"])
|
||||||
|
}
|
||||||
|
if version := asString(itm["version"]); version != "" {
|
||||||
|
title += " (" + version + ")"
|
||||||
|
}
|
||||||
|
artist := nestedSearchString(itm, "artist", "name")
|
||||||
|
if artist == "" {
|
||||||
|
artist = nestedSearchString(itm, "performer", "name")
|
||||||
|
}
|
||||||
|
album := nestedSearchString(itm, "album", "title")
|
||||||
|
trackCount := searchInt(itm["tracks_count"])
|
||||||
|
if trackCount == 0 {
|
||||||
|
trackCount = searchInt(itm["track_count"])
|
||||||
|
}
|
||||||
|
explicit := searchBool(itm["parental_warning"])
|
||||||
|
date := firstNonEmpty(
|
||||||
|
asString(itm["release_date_original"]),
|
||||||
|
asString(itm["release_date"]),
|
||||||
|
asString(itm["releaseDate"]),
|
||||||
|
asString(itm["streamStartDate"]),
|
||||||
|
nestedSearchString(itm, "album", "release_date_original"),
|
||||||
|
nestedSearchString(itm, "album", "release_date"),
|
||||||
|
)
|
||||||
|
releases := 0
|
||||||
|
if mediaType == "artist" {
|
||||||
|
releases = firstPositiveInt(
|
||||||
|
searchInt(itm["albums_count"]),
|
||||||
|
searchInt(itm["albumsCount"]),
|
||||||
|
nestedSearchInt(itm, "albums", "total"),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
appendUnique(searchResult{ID: id, Title: title, Artist: artist, Album: album, Date: date, Releases: releases, TrackCount: trackCount, Explicit: explicit})
|
||||||
|
}
|
||||||
|
case "tidal":
|
||||||
|
items, ok := page["items"].([]any)
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, raw := range items {
|
||||||
|
itm, ok := raw.(map[string]any)
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if wrapped, ok := itm["item"].(map[string]any); ok {
|
||||||
|
itm = wrapped
|
||||||
|
}
|
||||||
|
id := asString(itm["id"])
|
||||||
|
title := asString(itm["title"])
|
||||||
|
if title == "" {
|
||||||
|
title = asString(itm["name"])
|
||||||
|
}
|
||||||
|
artist := nestedSearchString(itm, "artist", "name")
|
||||||
|
if artist == "" {
|
||||||
|
if artists, ok := itm["artists"].([]any); ok && len(artists) > 0 {
|
||||||
|
if a0, ok := artists[0].(map[string]any); ok {
|
||||||
|
artist = asString(a0["name"])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
album := nestedSearchString(itm, "album", "title")
|
||||||
|
trackCount := searchInt(itm["numberOfTracks"])
|
||||||
|
if trackCount == 0 {
|
||||||
|
trackCount = searchInt(itm["tracks_count"])
|
||||||
|
}
|
||||||
|
explicit := searchBool(itm["explicit"])
|
||||||
|
date := firstNonEmpty(
|
||||||
|
asString(itm["releaseDate"]),
|
||||||
|
asString(itm["streamStartDate"]),
|
||||||
|
asString(itm["release_date"]),
|
||||||
|
nestedSearchString(itm, "album", "releaseDate"),
|
||||||
|
nestedSearchString(itm, "album", "release_date"),
|
||||||
|
)
|
||||||
|
releases := 0
|
||||||
|
if mediaType == "artist" {
|
||||||
|
releases = firstPositiveInt(
|
||||||
|
searchInt(itm["numberOfAlbums"]),
|
||||||
|
searchInt(itm["albums_count"]),
|
||||||
|
searchInt(itm["albumsCount"]),
|
||||||
|
nestedSearchInt(itm, "albums", "total"),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
appendUnique(searchResult{ID: id, Title: title, Artist: artist, Album: album, Date: date, Releases: releases, TrackCount: trackCount, Explicit: explicit})
|
||||||
|
}
|
||||||
|
case "deezer":
|
||||||
|
key := mediaType + "s"
|
||||||
|
bucket, ok := page[key].(map[string]any)
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
items, ok := bucket["items"].([]any)
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, raw := range items {
|
||||||
|
itm, ok := raw.(map[string]any)
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
id := asString(itm["id"])
|
||||||
|
title := asString(itm["title"])
|
||||||
|
if title == "" {
|
||||||
|
title = asString(itm["name"])
|
||||||
|
}
|
||||||
|
artist := nestedSearchString(itm, "artist", "name")
|
||||||
|
album := nestedSearchString(itm, "album", "title")
|
||||||
|
trackCount := searchInt(itm["nb_tracks"])
|
||||||
|
explicit := searchBool(itm["explicit_lyrics"])
|
||||||
|
date := firstNonEmpty(
|
||||||
|
asString(itm["release_date"]),
|
||||||
|
nestedSearchString(itm, "album", "release_date"),
|
||||||
|
)
|
||||||
|
releases := 0
|
||||||
|
if mediaType == "artist" {
|
||||||
|
releases = firstPositiveInt(
|
||||||
|
searchInt(itm["nb_album"]),
|
||||||
|
searchInt(itm["albums_count"]),
|
||||||
|
searchInt(itm["numberOfAlbums"]),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
appendUnique(searchResult{ID: id, Title: title, Artist: artist, Album: album, Date: date, Releases: releases, TrackCount: trackCount, Explicit: explicit})
|
||||||
|
}
|
||||||
|
case "soundcloud":
|
||||||
|
items, ok := page["items"].([]any)
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, raw := range items {
|
||||||
|
itm, ok := raw.(map[string]any)
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
id := asString(itm["id"])
|
||||||
|
title := asString(itm["title"])
|
||||||
|
artist := nestedSearchString(itm, "artist", "name")
|
||||||
|
trackCount := searchInt(itm["tracks_count"])
|
||||||
|
date := firstNonEmpty(
|
||||||
|
asString(itm["release_date"]),
|
||||||
|
asString(itm["display_date"]),
|
||||||
|
)
|
||||||
|
appendUnique(searchResult{ID: id, Title: title, Artist: artist, Date: date, TrackCount: trackCount})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return results
|
||||||
|
}
|
||||||
|
|
||||||
|
func formatSearchDetails(mediaType string, r searchResult) string {
|
||||||
|
date := strings.TrimSpace(r.Date)
|
||||||
|
if date == "" {
|
||||||
|
date = "Unknown"
|
||||||
|
}
|
||||||
|
lines := []string{}
|
||||||
|
switch mediaType {
|
||||||
|
case "album":
|
||||||
|
lines = append(lines, "Date released:", date)
|
||||||
|
if r.TrackCount > 0 {
|
||||||
|
lines = append(lines, "", fmt.Sprintf("%d Tracks", r.TrackCount))
|
||||||
|
}
|
||||||
|
case "artist":
|
||||||
|
if strings.TrimSpace(r.Title) != "" {
|
||||||
|
lines = append(lines, r.Title)
|
||||||
|
}
|
||||||
|
if r.Releases > 0 {
|
||||||
|
lines = append(lines, "", fmt.Sprintf("%d Releases", r.Releases))
|
||||||
|
}
|
||||||
|
case "track":
|
||||||
|
lines = append(lines, "Released on:", date)
|
||||||
|
case "playlist":
|
||||||
|
if r.TrackCount > 0 {
|
||||||
|
lines = append(lines, fmt.Sprintf("%d Tracks", r.TrackCount))
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
if strings.TrimSpace(r.Title) != "" {
|
||||||
|
lines = append(lines, r.Title)
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(r.Artist) != "" {
|
||||||
|
lines = append(lines, strings.TrimSpace(r.Artist))
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(r.Album) != "" {
|
||||||
|
lines = append(lines, strings.TrimSpace(r.Album))
|
||||||
|
}
|
||||||
|
if r.TrackCount > 0 {
|
||||||
|
lines = append(lines, fmt.Sprintf("%d Tracks", r.TrackCount))
|
||||||
|
}
|
||||||
|
if r.Explicit {
|
||||||
|
lines = append(lines, "Explicit")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
lines = append(lines, "", "ID: "+r.ID)
|
||||||
|
return strings.Join(lines, "\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
func formatSearchOptionLabel(index int, mediaType string, r searchResult) string {
|
||||||
|
title := strings.TrimSpace(r.Title)
|
||||||
|
if title == "" {
|
||||||
|
title = "Unknown"
|
||||||
|
}
|
||||||
|
artist := strings.TrimSpace(r.Artist)
|
||||||
|
switch mediaType {
|
||||||
|
case "artist", "label":
|
||||||
|
return fmt.Sprintf("%d. %s", index, title)
|
||||||
|
default:
|
||||||
|
if artist == "" {
|
||||||
|
return fmt.Sprintf("%d. %s", index, title)
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("%d. %s by %s", index, title, artist)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func nestedSearchString(v map[string]any, keys ...string) string {
|
||||||
|
cur := any(v)
|
||||||
|
for _, key := range keys {
|
||||||
|
m, ok := cur.(map[string]any)
|
||||||
|
if !ok {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
cur = m[key]
|
||||||
|
}
|
||||||
|
return asString(cur)
|
||||||
|
}
|
||||||
|
|
||||||
|
func nestedSearchInt(v map[string]any, keys ...string) int {
|
||||||
|
cur := any(v)
|
||||||
|
for _, key := range keys {
|
||||||
|
m, ok := cur.(map[string]any)
|
||||||
|
if !ok {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
cur = m[key]
|
||||||
|
}
|
||||||
|
return searchInt(cur)
|
||||||
|
}
|
||||||
|
|
||||||
|
func firstPositiveInt(values ...int) int {
|
||||||
|
for _, v := range values {
|
||||||
|
if v > 0 {
|
||||||
|
return v
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func searchInt(v any) int {
|
||||||
|
switch t := v.(type) {
|
||||||
|
case int:
|
||||||
|
return t
|
||||||
|
case int64:
|
||||||
|
return int(t)
|
||||||
|
case float64:
|
||||||
|
return int(t)
|
||||||
|
case string:
|
||||||
|
i, _ := strconv.Atoi(t)
|
||||||
|
return i
|
||||||
|
default:
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func searchBool(v any) bool {
|
||||||
|
b, ok := v.(bool)
|
||||||
|
return ok && b
|
||||||
|
}
|
||||||
87
cmd/rip/search_test.go
Normal file
87
cmd/rip/search_test.go
Normal file
@@ -0,0 +1,87 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestFormatSearchDetailsAlbum(t *testing.T) {
|
||||||
|
r := searchResult{ID: "9399700017915", Date: "1994-02-01", TrackCount: 18}
|
||||||
|
got := formatSearchDetails("album", r)
|
||||||
|
want := "Date released:\n1994-02-01\n\n18 Tracks\n\nID: 9399700017915"
|
||||||
|
if got != want {
|
||||||
|
t.Fatalf("unexpected album details:\n%s", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFormatSearchDetailsTrackDefaultsDate(t *testing.T) {
|
||||||
|
r := searchResult{ID: "3083287"}
|
||||||
|
got := formatSearchDetails("track", r)
|
||||||
|
want := "Released on:\nUnknown\n\nID: 3083287"
|
||||||
|
if got != want {
|
||||||
|
t.Fatalf("unexpected track details:\n%s", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFormatSearchDetailsArtistWithReleases(t *testing.T) {
|
||||||
|
r := searchResult{ID: "1863897", Title: "Lost Frequencies", Releases: 23}
|
||||||
|
got := formatSearchDetails("artist", r)
|
||||||
|
want := "Lost Frequencies\n\n23 Releases\n\nID: 1863897"
|
||||||
|
if got != want {
|
||||||
|
t.Fatalf("unexpected artist details:\n%s", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNormalizeSearchResultsQobuzExtractsDate(t *testing.T) {
|
||||||
|
pages := []map[string]any{
|
||||||
|
{"albums": map[string]any{"items": []any{
|
||||||
|
map[string]any{
|
||||||
|
"id": "1",
|
||||||
|
"title": "Master of Reality",
|
||||||
|
"release_date_original": "1971-07-21",
|
||||||
|
"artist": map[string]any{"name": "Black Sabbath"},
|
||||||
|
},
|
||||||
|
}}},
|
||||||
|
}
|
||||||
|
results := normalizeSearchResults("qobuz", "album", pages)
|
||||||
|
if len(results) != 1 {
|
||||||
|
t.Fatalf("len(results)=%d want 1", len(results))
|
||||||
|
}
|
||||||
|
if results[0].Date != "1971-07-21" {
|
||||||
|
t.Fatalf("date=%q want 1971-07-21", results[0].Date)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFormatSearchOptionLabelArtistNoUnknownArtistSuffix(t *testing.T) {
|
||||||
|
r := searchResult{Title: "Lost Frequencies"}
|
||||||
|
got := formatSearchOptionLabel(1, "artist", r)
|
||||||
|
want := "1. Lost Frequencies"
|
||||||
|
if got != want {
|
||||||
|
t.Fatalf("label=%q want %q", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFormatSearchOptionLabelTrackWithArtist(t *testing.T) {
|
||||||
|
r := searchResult{Title: "Dreams", Artist: "Fleetwood Mac"}
|
||||||
|
got := formatSearchOptionLabel(2, "track", r)
|
||||||
|
want := "2. Dreams by Fleetwood Mac"
|
||||||
|
if got != want {
|
||||||
|
t.Fatalf("label=%q want %q", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNormalizeSearchResultsQobuzArtistExtractsReleases(t *testing.T) {
|
||||||
|
pages := []map[string]any{
|
||||||
|
{"artists": map[string]any{"items": []any{
|
||||||
|
map[string]any{
|
||||||
|
"id": "1863897",
|
||||||
|
"name": "Lost Frequencies",
|
||||||
|
"albums_count": 23,
|
||||||
|
},
|
||||||
|
}}},
|
||||||
|
}
|
||||||
|
results := normalizeSearchResults("qobuz", "artist", pages)
|
||||||
|
if len(results) != 1 {
|
||||||
|
t.Fatalf("len(results)=%d want 1", len(results))
|
||||||
|
}
|
||||||
|
if results[0].Releases != 23 {
|
||||||
|
t.Fatalf("releases=%d want 23", results[0].Releases)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -18,7 +18,8 @@ requests_per_minute = 60
|
|||||||
verify_ssl = true
|
verify_ssl = true
|
||||||
|
|
||||||
[qobuz]
|
[qobuz]
|
||||||
# 1: 320kbps MP3, 2: 16/44.1, 3: 24/<=96, 4: 24/>96
|
# Quality ladder (global scale is 0-4, Qobuz supports 1-4):
|
||||||
|
# 1 = MP3 320, 2 = FLAC 16/44.1, 3 = FLAC 24-bit <=96kHz, 4 = FLAC 24-bit <=192kHz
|
||||||
quality = 3
|
quality = 3
|
||||||
# Download booklet PDFs when available
|
# Download booklet PDFs when available
|
||||||
download_booklets = true
|
download_booklets = true
|
||||||
@@ -35,7 +36,9 @@ app_id = ""
|
|||||||
secrets = []
|
secrets = []
|
||||||
|
|
||||||
[tidal]
|
[tidal]
|
||||||
# 0: AAC 256, 1: AAC 320, 2: FLAC 16/44.1, 3: FLAC hi-res when available
|
# Quality ladder:
|
||||||
|
# 0 = LOW (HEAACV1), 1 = HIGH (AACLC), 2 = LOSSLESS (FLAC), 3/4 = HI_RES_LOSSLESS when available
|
||||||
|
# If a tier is unavailable, Tidal may fall back to the best available stream for that track.
|
||||||
quality = 3
|
quality = 3
|
||||||
# Prefer Dolby Atmos/immersive stream variants when available
|
# Prefer Dolby Atmos/immersive stream variants when available
|
||||||
# Disabled by default because stereo FLAC is usually preferred
|
# Disabled by default because stereo FLAC is usually preferred
|
||||||
@@ -52,7 +55,8 @@ refresh_token = ""
|
|||||||
token_expiry = 0
|
token_expiry = 0
|
||||||
|
|
||||||
[deezer]
|
[deezer]
|
||||||
# 0: MP3_128, 1: MP3_320, 2: FLAC
|
# Quality ladder:
|
||||||
|
# 0 = MP3_128, 1 = MP3_320, 2/3/4 = FLAC
|
||||||
quality = 2
|
quality = 2
|
||||||
# If target quality is unavailable, fallback down quality ladder
|
# If target quality is unavailable, fallback down quality ladder
|
||||||
lower_quality_if_not_available = true
|
lower_quality_if_not_available = true
|
||||||
@@ -65,7 +69,7 @@ password = ""
|
|||||||
refresh_token = ""
|
refresh_token = ""
|
||||||
|
|
||||||
[soundcloud]
|
[soundcloud]
|
||||||
# Only 0 is currently supported
|
# Quality is currently provider-defined (keep 0)
|
||||||
quality = 0
|
quality = 0
|
||||||
# Managed automatically when available
|
# Managed automatically when available
|
||||||
client_id = ""
|
client_id = ""
|
||||||
@@ -131,7 +135,7 @@ exclude = []
|
|||||||
[filepaths]
|
[filepaths]
|
||||||
# Create folders for single tracks using folder_format template
|
# Create folders for single tracks using folder_format template
|
||||||
add_singles_to_folder = false
|
add_singles_to_folder = false
|
||||||
# Available keys: albumartist, title, year, bit_depth, sampling_rate, id, albumcomposer
|
# Available keys: albumartist, title, year, bit_depth, sampling_rate, id, container, codec, quality, bitrate, albumcomposer
|
||||||
folder_format = "{albumartist} - {title} ({year}) [{container}] [{bit_depth}B-{sampling_rate}kHz]"
|
folder_format = "{albumartist} - {title} ({year}) [{container}] [{bit_depth}B-{sampling_rate}kHz]"
|
||||||
# Available keys: id, tracknumber, artist, albumartist, composer, title, albumcomposer, explicit
|
# Available keys: id, tracknumber, artist, albumartist, composer, title, albumcomposer, explicit
|
||||||
track_format = "{tracknumber:02}. {artist} - {title}{explicit}"
|
track_format = "{tracknumber:02}. {artist} - {title}{explicit}"
|
||||||
|
|||||||
@@ -2,7 +2,9 @@ package app
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"os/exec"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"regexp"
|
"regexp"
|
||||||
"sort"
|
"sort"
|
||||||
@@ -16,6 +18,7 @@ import (
|
|||||||
"streamrip-go/internal/config"
|
"streamrip-go/internal/config"
|
||||||
"streamrip-go/internal/domain/media"
|
"streamrip-go/internal/domain/media"
|
||||||
"streamrip-go/internal/download"
|
"streamrip-go/internal/download"
|
||||||
|
"streamrip-go/internal/jsonutil"
|
||||||
"streamrip-go/internal/naming"
|
"streamrip-go/internal/naming"
|
||||||
"streamrip-go/internal/provider"
|
"streamrip-go/internal/provider"
|
||||||
deezerprovider "streamrip-go/internal/provider/deezer"
|
deezerprovider "streamrip-go/internal/provider/deezer"
|
||||||
@@ -45,6 +48,7 @@ type ripTrackOptions struct {
|
|||||||
albumFolder string
|
albumFolder string
|
||||||
albumEmbedCover string
|
albumEmbedCover string
|
||||||
albumArtist string
|
albumArtist string
|
||||||
|
prefetched *provider.Downloadable
|
||||||
index int
|
index int
|
||||||
total int
|
total int
|
||||||
albumDiscTotal int
|
albumDiscTotal int
|
||||||
@@ -53,6 +57,15 @@ type ripTrackOptions struct {
|
|||||||
playlistPos int
|
playlistPos int
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type folderAudioValues struct {
|
||||||
|
container string
|
||||||
|
codec string
|
||||||
|
quality string
|
||||||
|
bitDepth int
|
||||||
|
samplingRate string
|
||||||
|
bitrateKbps int
|
||||||
|
}
|
||||||
|
|
||||||
type collectionAlbum struct {
|
type collectionAlbum struct {
|
||||||
ID string
|
ID string
|
||||||
Meta map[string]any
|
Meta map[string]any
|
||||||
@@ -78,6 +91,10 @@ type videoDownloadableProvider interface {
|
|||||||
GetVideoDownloadable(ctx context.Context, videoID string) (*provider.Downloadable, error)
|
GetVideoDownloadable(ctx context.Context, videoID string) (*provider.Downloadable, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type trackFallbackDownloader interface {
|
||||||
|
DownloadTrackFallback(ctx context.Context, trackID string, quality int, outputPath string) error
|
||||||
|
}
|
||||||
|
|
||||||
func New(cfg *config.Config) (*Main, error) {
|
func New(cfg *config.Config) (*Main, error) {
|
||||||
var db store.Database
|
var db store.Database
|
||||||
if cfg.Session.Database.DownloadsEnabled || cfg.Session.Database.FailedDownloadsEnabled {
|
if cfg.Session.Database.DownloadsEnabled || cfg.Session.Database.FailedDownloadsEnabled {
|
||||||
@@ -101,13 +118,24 @@ func New(cfg *config.Config) (*Main, error) {
|
|||||||
Config: cfg,
|
Config: cfg,
|
||||||
Providers: providers,
|
Providers: providers,
|
||||||
Store: db,
|
Store: db,
|
||||||
DL: download.NewWithOptions(cfg.Session.Downloads.VerifySSL, cfg.Session.CLI.ProgressBars),
|
DL: download.NewWithOptions(cfg.Session.Downloads.VerifySSL, cfg.Session.CLI.ProgressBars, downloaderMaxConnsPerHost(cfg.Session.Downloads.MaxConnections)),
|
||||||
Tagger: tag.New(),
|
Tagger: tag.New(),
|
||||||
Pending: []media.Pending{},
|
Pending: []media.Pending{},
|
||||||
Media: []media.Media{},
|
Media: []media.Media{},
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// downloaderMaxConnsPerHost picks the per-host idle connection cap for the
|
||||||
|
// shared download client. We floor at 16 so artwork/manifest fetches and
|
||||||
|
// concurrent track downloads to the same CDN host can reuse keep-alive
|
||||||
|
// sockets even when the user configured a tiny max_connections.
|
||||||
|
func downloaderMaxConnsPerHost(maxConnections int) int {
|
||||||
|
if maxConnections > 16 {
|
||||||
|
return maxConnections
|
||||||
|
}
|
||||||
|
return 16
|
||||||
|
}
|
||||||
|
|
||||||
func (m *Main) Close() error {
|
func (m *Main) Close() error {
|
||||||
m.DL.Close()
|
m.DL.Close()
|
||||||
artwork.CleanupTempDirs()
|
artwork.CleanupTempDirs()
|
||||||
@@ -257,7 +285,7 @@ func (m *Main) AddMixedPlaylistByTrackRefs(ctx context.Context, playlistID, play
|
|||||||
|
|
||||||
func (m *Main) ripCollection(ctx context.Context, p provider.Client, source, kind, id string, meta map[string]any) error {
|
func (m *Main) ripCollection(ctx context.Context, p provider.Client, source, kind, id string, meta map[string]any) error {
|
||||||
name := titleFromMetadata(meta, id)
|
name := titleFromMetadata(meta, id)
|
||||||
if n := stringFromAny(meta["name"]); n != "" {
|
if n := jsonutil.StringFromAny(meta["name"]); n != "" {
|
||||||
name = n
|
name = n
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -325,18 +353,18 @@ func (m *Main) ripVideo(ctx context.Context, p provider.Client, source, videoID
|
|||||||
}
|
}
|
||||||
|
|
||||||
func buildCollectionAlbum(id string, meta map[string]any) collectionAlbum {
|
func buildCollectionAlbum(id string, meta map[string]any) collectionAlbum {
|
||||||
trackCount := intFromAny(meta["tracks_count"])
|
trackCount := jsonutil.IntFromAny(meta["tracks_count"])
|
||||||
if trackCount == 0 {
|
if trackCount == 0 {
|
||||||
trackCount = intFromAny(meta["numberOfTracks"])
|
trackCount = jsonutil.IntFromAny(meta["numberOfTracks"])
|
||||||
}
|
}
|
||||||
return collectionAlbum{
|
return collectionAlbum{
|
||||||
ID: id,
|
ID: id,
|
||||||
Meta: meta,
|
Meta: meta,
|
||||||
Title: titleFromMetadata(meta, id),
|
Title: titleFromMetadata(meta, id),
|
||||||
AlbumArtist: nestedString(meta, "artist", "name"),
|
AlbumArtist: jsonutil.NestedString(meta, "artist", "name"),
|
||||||
BitDepth: intFromAny(meta["maximum_bit_depth"]),
|
BitDepth: jsonutil.IntFromAny(meta["maximum_bit_depth"]),
|
||||||
Sampling: floatFromAny(meta["maximum_sampling_rate"]),
|
Sampling: jsonutil.FloatFromAny(meta["maximum_sampling_rate"]),
|
||||||
Explicit: boolFromAny(meta["parental_warning"]),
|
Explicit: jsonutil.BoolFromAny(meta["parental_warning"]),
|
||||||
TrackCount: trackCount,
|
TrackCount: trackCount,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -457,10 +485,10 @@ func extractAlbumIDs(meta map[string]any) []string {
|
|||||||
if !ok {
|
if !ok {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
id := stringFromAny(itm["id"])
|
id := jsonutil.StringFromAny(itm["id"])
|
||||||
if id == "" {
|
if id == "" {
|
||||||
if nested, ok := itm["album"].(map[string]any); ok {
|
if nested, ok := itm["album"].(map[string]any); ok {
|
||||||
id = stringFromAny(nested["id"])
|
id = jsonutil.StringFromAny(nested["id"])
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if id == "" {
|
if id == "" {
|
||||||
@@ -515,32 +543,23 @@ func (m *Main) ripAlbum(ctx context.Context, p provider.Client, source, albumID
|
|||||||
}
|
}
|
||||||
|
|
||||||
albumTitle := titleFromMetadata(albumMeta, albumID)
|
albumTitle := titleFromMetadata(albumMeta, albumID)
|
||||||
albumArtist := nestedString(albumMeta, "artist", "name")
|
albumArtist := jsonutil.NestedString(albumMeta, "artist", "name")
|
||||||
if albumArtist == "" {
|
if albumArtist == "" {
|
||||||
albumArtist = "Unknown"
|
albumArtist = "Unknown"
|
||||||
}
|
}
|
||||||
releaseDate := stringFromAny(albumMeta["release_date_original"])
|
releaseDate := jsonutil.StringFromAny(albumMeta["release_date_original"])
|
||||||
if releaseDate == "" {
|
if releaseDate == "" {
|
||||||
releaseDate = stringFromAny(albumMeta["release_date"])
|
releaseDate = jsonutil.StringFromAny(albumMeta["release_date"])
|
||||||
}
|
}
|
||||||
if releaseDate == "" {
|
if releaseDate == "" {
|
||||||
releaseDate = stringFromAny(albumMeta["releaseDate"])
|
releaseDate = jsonutil.StringFromAny(albumMeta["releaseDate"])
|
||||||
}
|
}
|
||||||
if releaseDate == "" {
|
if releaseDate == "" {
|
||||||
releaseDate = stringFromAny(albumMeta["streamStartDate"])
|
releaseDate = jsonutil.StringFromAny(albumMeta["streamStartDate"])
|
||||||
}
|
}
|
||||||
year := naming.YearFromDate(releaseDate)
|
year := naming.YearFromDate(releaseDate)
|
||||||
bitDepth := intFromAny(albumMeta["maximum_bit_depth"])
|
bitDepth := jsonutil.IntFromAny(albumMeta["maximum_bit_depth"])
|
||||||
sampling := stringFromAny(albumMeta["maximum_sampling_rate"])
|
sampling := jsonutil.StringFromAny(albumMeta["maximum_sampling_rate"])
|
||||||
if bitDepth == 0 || sampling == "" {
|
|
||||||
fallbackBitDepth, fallbackSampling := m.qualityProfileForSource(source)
|
|
||||||
if bitDepth == 0 {
|
|
||||||
bitDepth = fallbackBitDepth
|
|
||||||
}
|
|
||||||
if sampling == "" {
|
|
||||||
sampling = fallbackSampling
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
tracksMap, ok := albumMeta["tracks"].(map[string]any)
|
tracksMap, ok := albumMeta["tracks"].(map[string]any)
|
||||||
if !ok {
|
if !ok {
|
||||||
@@ -562,18 +581,25 @@ func (m *Main) ripAlbum(ctx context.Context, p provider.Client, source, albumID
|
|||||||
if !ok {
|
if !ok {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
id := stringFromAny(itm["id"])
|
id := jsonutil.StringFromAny(itm["id"])
|
||||||
if id != "" {
|
if id != "" {
|
||||||
trackIDs = append(trackIDs, id)
|
trackIDs = append(trackIDs, id)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
folder := m.albumFolderPath(source, albumID, albumTitle, albumArtist, year, bitDepth, sampling)
|
var prefetched *provider.Downloadable
|
||||||
|
if len(trackIDs) > 0 {
|
||||||
|
if d, dErr := p.GetDownloadable(ctx, trackIDs[0], m.qualityForSource(source)); dErr == nil {
|
||||||
|
prefetched = d
|
||||||
|
}
|
||||||
|
}
|
||||||
|
audioVals := m.folderAudioValues(source, bitDepth, sampling, prefetched)
|
||||||
|
folder := m.albumFolderPath(source, albumID, albumTitle, albumArtist, year, audioVals)
|
||||||
artRes, _ := artwork.Prepare(ctx, m.DL, folder, albumMeta, m.Config.Session.Artwork, false)
|
artRes, _ := artwork.Prepare(ctx, m.DL, folder, albumMeta, m.Config.Session.Artwork, false)
|
||||||
total := len(trackIDs)
|
total := len(trackIDs)
|
||||||
discTotal := intFromAny(albumMeta["media_count"])
|
discTotal := jsonutil.IntFromAny(albumMeta["media_count"])
|
||||||
if discTotal == 0 {
|
if discTotal == 0 {
|
||||||
discTotal = intFromAny(albumMeta["numberOfVolumes"])
|
discTotal = jsonutil.IntFromAny(albumMeta["numberOfVolumes"])
|
||||||
}
|
}
|
||||||
m.logf("Album: %s (%d tracks)\n", albumTitle, total)
|
m.logf("Album: %s (%d tracks)\n", albumTitle, total)
|
||||||
failures := 0
|
failures := 0
|
||||||
@@ -581,6 +607,9 @@ func (m *Main) ripAlbum(ctx context.Context, p provider.Client, source, albumID
|
|||||||
if !m.Config.Session.Downloads.Concurrency || m.Config.Session.Downloads.MaxConnections == 1 {
|
if !m.Config.Session.Downloads.Concurrency || m.Config.Session.Downloads.MaxConnections == 1 {
|
||||||
for i, trackID := range trackIDs {
|
for i, trackID := range trackIDs {
|
||||||
opts := ripTrackOptions{albumFolder: folder, albumEmbedCover: artRes.EmbedPath, albumArtist: albumArtist, index: i + 1, total: total, albumDiscTotal: discTotal}
|
opts := ripTrackOptions{albumFolder: folder, albumEmbedCover: artRes.EmbedPath, albumArtist: albumArtist, index: i + 1, total: total, albumDiscTotal: discTotal}
|
||||||
|
if i == 0 {
|
||||||
|
opts.prefetched = prefetched
|
||||||
|
}
|
||||||
if err := m.ripTrack(ctx, p, source, trackID, "", opts); err != nil {
|
if err := m.ripTrack(ctx, p, source, trackID, "", opts); err != nil {
|
||||||
failures++
|
failures++
|
||||||
m.logf("track failed: id=%s reason=%v\n", trackID, err)
|
m.logf("track failed: id=%s reason=%v\n", trackID, err)
|
||||||
@@ -606,6 +635,9 @@ func (m *Main) ripAlbum(ctx context.Context, p provider.Client, source, albumID
|
|||||||
defer wg.Done()
|
defer wg.Done()
|
||||||
defer func() { <-sem }()
|
defer func() { <-sem }()
|
||||||
opts := ripTrackOptions{albumFolder: folder, albumEmbedCover: artRes.EmbedPath, albumArtist: albumArtist, index: idx, total: total, albumDiscTotal: discTotal}
|
opts := ripTrackOptions{albumFolder: folder, albumEmbedCover: artRes.EmbedPath, albumArtist: albumArtist, index: idx, total: total, albumDiscTotal: discTotal}
|
||||||
|
if idx == 1 {
|
||||||
|
opts.prefetched = prefetched
|
||||||
|
}
|
||||||
if err := m.ripTrack(ctx, p, source, tid, "", opts); err != nil {
|
if err := m.ripTrack(ctx, p, source, tid, "", opts); err != nil {
|
||||||
errCh <- err
|
errCh <- err
|
||||||
}
|
}
|
||||||
@@ -629,12 +661,12 @@ func (m *Main) ripPlaylist(ctx context.Context, p provider.Client, source, playl
|
|||||||
}
|
}
|
||||||
|
|
||||||
name := titleFromMetadata(playlistMeta, playlistID)
|
name := titleFromMetadata(playlistMeta, playlistID)
|
||||||
if n := stringFromAny(playlistMeta["name"]); n != "" {
|
if n := jsonutil.StringFromAny(playlistMeta["name"]); n != "" {
|
||||||
name = n
|
name = n
|
||||||
}
|
}
|
||||||
base := m.Config.Session.Downloads.Folder
|
base := m.Config.Session.Downloads.Folder
|
||||||
if m.Config.Session.Downloads.SourceSubdirectories {
|
if m.Config.Session.Downloads.SourceSubdirectories {
|
||||||
base = filepath.Join(base, strings.Title(source))
|
base = filepath.Join(base, jsonutil.TitleCase(source))
|
||||||
}
|
}
|
||||||
folder := filepath.Join(base, naming.CleanName(name, naming.Config{
|
folder := filepath.Join(base, naming.CleanName(name, naming.Config{
|
||||||
RestrictCharacters: m.Config.Session.Filepaths.RestrictCharacters,
|
RestrictCharacters: m.Config.Session.Filepaths.RestrictCharacters,
|
||||||
@@ -663,9 +695,9 @@ func (m *Main) ripPlaylist(ctx context.Context, p provider.Client, source, playl
|
|||||||
if !ok {
|
if !ok {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
id := stringFromAny(itm["id"])
|
id := jsonutil.StringFromAny(itm["id"])
|
||||||
if id == "" {
|
if id == "" {
|
||||||
id = stringFromAny(itm["track_id"])
|
id = jsonutil.StringFromAny(itm["track_id"])
|
||||||
}
|
}
|
||||||
if id != "" {
|
if id != "" {
|
||||||
ids = append(ids, id)
|
ids = append(ids, id)
|
||||||
@@ -804,11 +836,9 @@ func (m *Main) requireSourceDownloadAuth(source string) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (m *Main) ripTrack(ctx context.Context, p provider.Client, source, id, fallbackTitle string, opts ripTrackOptions) error {
|
func (m *Main) ripTrack(ctx context.Context, p provider.Client, source, id, fallbackTitle string, opts ripTrackOptions) error {
|
||||||
|
if !m.IgnoreDB {
|
||||||
alreadyDownloaded, err := m.Store.IsDownloaded(ctx, source, id)
|
alreadyDownloaded, err := m.Store.IsDownloaded(ctx, source, id)
|
||||||
if err == nil && alreadyDownloaded {
|
if err == nil && alreadyDownloaded {
|
||||||
if m.IgnoreDB {
|
|
||||||
alreadyDownloaded = false
|
|
||||||
} else {
|
|
||||||
if opts.total > 0 {
|
if opts.total > 0 {
|
||||||
m.logf("[%d/%d] skip (already downloaded) id=%s\n", opts.index, opts.total, id)
|
m.logf("[%d/%d] skip (already downloaded) id=%s\n", opts.index, opts.total, id)
|
||||||
} else {
|
} else {
|
||||||
@@ -818,19 +848,6 @@ func (m *Main) ripTrack(ctx context.Context, p provider.Client, source, id, fall
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if m.IgnoreDB {
|
|
||||||
alreadyDownloaded = false
|
|
||||||
}
|
|
||||||
|
|
||||||
if alreadyDownloaded {
|
|
||||||
if opts.total > 0 {
|
|
||||||
m.logf("[%d/%d] skip (already downloaded) id=%s\n", opts.index, opts.total, id)
|
|
||||||
} else {
|
|
||||||
m.logf("skip (already downloaded) id=%s\n", id)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
meta, err := p.GetMetadata(ctx, id, "track")
|
meta, err := p.GetMetadata(ctx, id, "track")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
_ = m.Store.MarkFailed(ctx, source, "track", id)
|
_ = m.Store.MarkFailed(ctx, source, "track", id)
|
||||||
@@ -846,13 +863,16 @@ func (m *Main) ripTrack(ctx context.Context, p provider.Client, source, id, fall
|
|||||||
applyPlaylistMetadataOverrides(meta, m.Config.Session.Metadata, opts.playlistName, opts.playlistPos)
|
applyPlaylistMetadataOverrides(meta, m.Config.Session.Metadata, opts.playlistName, opts.playlistPos)
|
||||||
}
|
}
|
||||||
|
|
||||||
d, err := p.GetDownloadable(ctx, id, m.qualityForSource(source))
|
d := opts.prefetched
|
||||||
|
if d == nil {
|
||||||
|
d, err = p.GetDownloadable(ctx, id, m.qualityForSource(source))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
_ = m.Store.MarkFailed(ctx, source, "track", id)
|
_ = m.Store.MarkFailed(ctx, source, "track", id)
|
||||||
return fmt.Errorf("id=%s title=%q get_downloadable: %w", id, title, err)
|
return fmt.Errorf("id=%s title=%q get_downloadable: %w", id, title, err)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
outPath := m.trackOutputPath(source, id, title, d.Extension, meta, opts.albumFolder, opts.albumDiscTotal)
|
outPath := m.trackOutputPath(source, id, title, d.Extension, d, meta, opts.albumFolder, opts.albumDiscTotal)
|
||||||
if opts.total > 0 && (!m.Config.Session.CLI.ProgressBars || !m.Config.Session.CLI.TextOutput || !m.DL.ProgressEnabled()) {
|
if opts.total > 0 && (!m.Config.Session.CLI.ProgressBars || !m.Config.Session.CLI.TextOutput || !m.DL.ProgressEnabled()) {
|
||||||
m.logf("[%d/%d] %s\n", opts.index, opts.total, filepath.Base(outPath))
|
m.logf("[%d/%d] %s\n", opts.index, opts.total, filepath.Base(outPath))
|
||||||
}
|
}
|
||||||
@@ -869,11 +889,21 @@ func (m *Main) ripTrack(ctx context.Context, p provider.Client, source, id, fall
|
|||||||
if err = downloadOnce(); err != nil {
|
if err = downloadOnce(); err != nil {
|
||||||
m.logf("retry: %s (%v)\n", filepath.Base(outPath), err)
|
m.logf("retry: %s (%v)\n", filepath.Base(outPath), err)
|
||||||
if err = downloadOnce(); err != nil {
|
if err = downloadOnce(); err != nil {
|
||||||
|
if fallbackProvider, ok := p.(trackFallbackDownloader); ok {
|
||||||
|
m.logf("fallback: %s via provider backup flow\n", filepath.Base(outPath))
|
||||||
|
if fbErr := fallbackProvider.DownloadTrackFallback(ctx, id, m.qualityForSource(source), outPath); fbErr == nil {
|
||||||
|
goto downloaded
|
||||||
|
} else {
|
||||||
|
m.logf("fallback failed: %s (%v)\n", filepath.Base(outPath), fbErr)
|
||||||
|
}
|
||||||
|
}
|
||||||
_ = m.Store.MarkFailed(ctx, source, "track", id)
|
_ = m.Store.MarkFailed(ctx, source, "track", id)
|
||||||
return fmt.Errorf("id=%s title=%q download: %w", id, title, err)
|
return fmt.Errorf("id=%s title=%q download: %w", id, title, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
downloaded:
|
||||||
|
|
||||||
embedCoverPath := opts.albumEmbedCover
|
embedCoverPath := opts.albumEmbedCover
|
||||||
if opts.forPlaylist {
|
if opts.forPlaylist {
|
||||||
parent := opts.albumFolder
|
parent := opts.albumFolder
|
||||||
@@ -903,6 +933,10 @@ func (m *Main) ripTrack(ctx context.Context, p provider.Client, source, id, fall
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if err = m.Tagger.TagFLAC(outPath, tagMeta, coverPath); err != nil {
|
if err = m.Tagger.TagFLAC(outPath, tagMeta, coverPath); err != nil {
|
||||||
|
if isFFmpegMissingError(err) {
|
||||||
|
_ = m.Store.MarkFailed(ctx, source, "track", id)
|
||||||
|
return fmt.Errorf("id=%s title=%q tag: %w", id, title, err)
|
||||||
|
}
|
||||||
m.logf("warning: tag failed for %s: %v\n", filepath.Base(outPath), err)
|
m.logf("warning: tag failed for %s: %v\n", filepath.Base(outPath), err)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -961,20 +995,95 @@ func (m *Main) qualityProfileForSource(source string) (int, string) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *Main) albumFolderPath(source, albumID, albumTitle, albumArtist, year string, bitDepth int, samplingRate string) string {
|
func (m *Main) folderAudioValues(source string, metaBitDepth int, metaSampling string, d *provider.Downloadable) folderAudioValues {
|
||||||
base := m.Config.Session.Downloads.Folder
|
vals := folderAudioValues{
|
||||||
if m.Config.Session.Downloads.SourceSubdirectories {
|
container: "FLAC",
|
||||||
base = filepath.Join(base, strings.Title(source))
|
bitDepth: metaBitDepth,
|
||||||
|
quality: "Unknown",
|
||||||
|
codec: "Unknown",
|
||||||
|
}
|
||||||
|
if s := strings.TrimSpace(metaSampling); s != "" {
|
||||||
|
vals.samplingRate = s
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if d != nil {
|
||||||
|
if c := strings.TrimSpace(d.Audio.Container); c != "" {
|
||||||
|
vals.container = strings.ToUpper(c)
|
||||||
|
} else if c := containerFromExtension(d.Extension); c != "" {
|
||||||
|
vals.container = c
|
||||||
|
}
|
||||||
|
if d.Audio.BitDepth > 0 {
|
||||||
|
vals.bitDepth = d.Audio.BitDepth
|
||||||
|
}
|
||||||
|
if s := strings.TrimSpace(d.Audio.SamplingRate); s != "" {
|
||||||
|
vals.samplingRate = s
|
||||||
|
}
|
||||||
|
if c := strings.TrimSpace(d.Audio.Codec); c != "" {
|
||||||
|
vals.codec = c
|
||||||
|
}
|
||||||
|
if q := strings.TrimSpace(d.Audio.Quality); q != "" {
|
||||||
|
vals.quality = q
|
||||||
|
}
|
||||||
|
if d.Audio.BitrateKbps > 0 {
|
||||||
|
vals.bitrateKbps = d.Audio.BitrateKbps
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if vals.bitDepth == 0 || vals.samplingRate == "" {
|
||||||
|
fallbackBitDepth, fallbackSampling := m.qualityProfileForSource(source)
|
||||||
|
if vals.bitDepth == 0 {
|
||||||
|
vals.bitDepth = fallbackBitDepth
|
||||||
|
}
|
||||||
|
if vals.samplingRate == "" {
|
||||||
|
vals.samplingRate = fallbackSampling
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if vals.codec == "Unknown" {
|
||||||
|
vals.codec = vals.container
|
||||||
|
}
|
||||||
|
return vals
|
||||||
|
}
|
||||||
|
|
||||||
|
func containerFromExtension(ext string) string {
|
||||||
|
switch strings.ToLower(strings.TrimSpace(ext)) {
|
||||||
|
case "flac":
|
||||||
|
return "FLAC"
|
||||||
|
case "mp3":
|
||||||
|
return "MP3"
|
||||||
|
case "m4a", "aac":
|
||||||
|
return "M4A"
|
||||||
|
case "mka":
|
||||||
|
return "MKA"
|
||||||
|
default:
|
||||||
|
v := strings.ToUpper(strings.TrimSpace(ext))
|
||||||
|
if v == "" {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return v
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Main) albumFolderPath(source, albumID, albumTitle, albumArtist, year string, audio folderAudioValues) string {
|
||||||
|
base := m.Config.Session.Downloads.Folder
|
||||||
|
if m.Config.Session.Downloads.SourceSubdirectories {
|
||||||
|
base = filepath.Join(base, jsonutil.TitleCase(source))
|
||||||
|
}
|
||||||
|
|
||||||
|
bitrate := "Unknown"
|
||||||
|
if audio.bitrateKbps > 0 {
|
||||||
|
bitrate = strconv.Itoa(audio.bitrateKbps)
|
||||||
|
}
|
||||||
vals := map[string]string{
|
vals := map[string]string{
|
||||||
"albumartist": albumArtist,
|
"albumartist": albumArtist,
|
||||||
"title": albumTitle,
|
"title": albumTitle,
|
||||||
"year": year,
|
"year": year,
|
||||||
"bit_depth": strconv.Itoa(bitDepth),
|
"bit_depth": strconv.Itoa(audio.bitDepth),
|
||||||
"sampling_rate": samplingRate,
|
"sampling_rate": audio.samplingRate,
|
||||||
"id": albumID,
|
"id": albumID,
|
||||||
"container": "FLAC",
|
"container": audio.container,
|
||||||
|
"codec": audio.codec,
|
||||||
|
"quality": audio.quality,
|
||||||
|
"bitrate": bitrate,
|
||||||
"albumcomposer": "Unknown",
|
"albumcomposer": "Unknown",
|
||||||
}
|
}
|
||||||
folderName := naming.FormatTemplate(m.Config.Session.Filepaths.FolderFormat, vals)
|
folderName := naming.FormatTemplate(m.Config.Session.Filepaths.FolderFormat, vals)
|
||||||
@@ -986,37 +1095,38 @@ func (m *Main) albumFolderPath(source, albumID, albumTitle, albumArtist, year st
|
|||||||
return filepath.Join(base, folderName)
|
return filepath.Join(base, folderName)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *Main) trackOutputPath(source, id, title, ext string, trackMeta map[string]any, albumFolder string, albumDiscTotal int) string {
|
func (m *Main) trackOutputPath(source, id, title, ext string, d *provider.Downloadable, trackMeta map[string]any, albumFolder string, albumDiscTotal int) string {
|
||||||
base := m.Config.Session.Downloads.Folder
|
base := m.Config.Session.Downloads.Folder
|
||||||
if m.Config.Session.Downloads.SourceSubdirectories {
|
if m.Config.Session.Downloads.SourceSubdirectories {
|
||||||
base = filepath.Join(base, strings.Title(source))
|
base = filepath.Join(base, jsonutil.TitleCase(source))
|
||||||
}
|
}
|
||||||
|
|
||||||
if albumFolder == "" && m.Config.Session.Filepaths.AddSinglesToFolder {
|
if albumFolder == "" && m.Config.Session.Filepaths.AddSinglesToFolder {
|
||||||
albumTitle := nestedString(trackMeta, "album", "title")
|
albumTitle := jsonutil.NestedString(trackMeta, "album", "title")
|
||||||
albumID := nestedString(trackMeta, "album", "id")
|
albumID := jsonutil.NestedString(trackMeta, "album", "id")
|
||||||
if albumID == "" {
|
if albumID == "" {
|
||||||
albumID = id
|
albumID = id
|
||||||
}
|
}
|
||||||
albumArtist := nestedString(trackMeta, "album", "artist", "name")
|
albumArtist := jsonutil.NestedString(trackMeta, "album", "artist", "name")
|
||||||
if albumArtist == "" {
|
if albumArtist == "" {
|
||||||
albumArtist = nestedString(trackMeta, "performer", "name")
|
albumArtist = jsonutil.NestedString(trackMeta, "performer", "name")
|
||||||
}
|
}
|
||||||
albumYear := naming.YearFromDate(stringFromAny(trackMeta["release_date_original"]))
|
albumYear := naming.YearFromDate(jsonutil.StringFromAny(trackMeta["release_date_original"]))
|
||||||
if albumYear == "Unknown" {
|
if albumYear == "Unknown" {
|
||||||
albumYear = naming.YearFromDate(stringFromAny(trackMeta["release_date"]))
|
albumYear = naming.YearFromDate(jsonutil.StringFromAny(trackMeta["release_date"]))
|
||||||
}
|
}
|
||||||
albumFolder = m.albumFolderPath(source, albumID, albumTitle, albumArtist, albumYear, intFromAny(trackMeta["maximum_bit_depth"]), stringFromAny(trackMeta["maximum_sampling_rate"]))
|
audioVals := m.folderAudioValues(source, jsonutil.IntFromAny(trackMeta["maximum_bit_depth"]), jsonutil.StringFromAny(trackMeta["maximum_sampling_rate"]), d)
|
||||||
|
albumFolder = m.albumFolderPath(source, albumID, albumTitle, albumArtist, albumYear, audioVals)
|
||||||
}
|
}
|
||||||
if albumFolder != "" {
|
if albumFolder != "" {
|
||||||
base = albumFolder
|
base = albumFolder
|
||||||
if m.Config.Session.Downloads.DiscSubdirectories && albumDiscTotal > 1 {
|
if m.Config.Session.Downloads.DiscSubdirectories && albumDiscTotal > 1 {
|
||||||
discNumber := intFromAny(trackMeta["media_number"])
|
discNumber := jsonutil.IntFromAny(trackMeta["media_number"])
|
||||||
if discNumber == 0 {
|
if discNumber == 0 {
|
||||||
discNumber = intFromAny(trackMeta["volumeNumber"])
|
discNumber = jsonutil.IntFromAny(trackMeta["volumeNumber"])
|
||||||
}
|
}
|
||||||
if discNumber == 0 {
|
if discNumber == 0 {
|
||||||
discNumber = intFromAny(trackMeta["disk_number"])
|
discNumber = jsonutil.IntFromAny(trackMeta["disk_number"])
|
||||||
}
|
}
|
||||||
if discNumber == 0 {
|
if discNumber == 0 {
|
||||||
discNumber = 1
|
discNumber = 1
|
||||||
@@ -1027,19 +1137,19 @@ func (m *Main) trackOutputPath(source, id, title, ext string, trackMeta map[stri
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
trackNumber := intFromAny(trackMeta["track_number"])
|
trackNumber := jsonutil.IntFromAny(trackMeta["track_number"])
|
||||||
if trackNumber == 0 {
|
if trackNumber == 0 {
|
||||||
trackNumber = intFromAny(trackMeta["trackNumber"])
|
trackNumber = jsonutil.IntFromAny(trackMeta["trackNumber"])
|
||||||
}
|
}
|
||||||
explicit := ""
|
explicit := ""
|
||||||
if boolFromAny(trackMeta["parental_warning"]) || boolFromAny(trackMeta["explicit"]) {
|
if jsonutil.BoolFromAny(trackMeta["parental_warning"]) || jsonutil.BoolFromAny(trackMeta["explicit"]) {
|
||||||
explicit = " (Explicit)"
|
explicit = " (Explicit)"
|
||||||
}
|
}
|
||||||
artist := nestedString(trackMeta, "performer", "name")
|
artist := jsonutil.NestedString(trackMeta, "performer", "name")
|
||||||
if artist == "" {
|
if artist == "" {
|
||||||
artist = nestedString(trackMeta, "artist", "name")
|
artist = jsonutil.NestedString(trackMeta, "artist", "name")
|
||||||
}
|
}
|
||||||
albumArtist := nestedString(trackMeta, "album", "artist", "name")
|
albumArtist := jsonutil.NestedString(trackMeta, "album", "artist", "name")
|
||||||
if albumArtist == "" {
|
if albumArtist == "" {
|
||||||
albumArtist = artist
|
albumArtist = artist
|
||||||
}
|
}
|
||||||
@@ -1067,7 +1177,7 @@ func (m *Main) videoOutputPath(source, id, title, ext string) string {
|
|||||||
}
|
}
|
||||||
base := m.Config.Session.Downloads.Folder
|
base := m.Config.Session.Downloads.Folder
|
||||||
if m.Config.Session.Downloads.SourceSubdirectories {
|
if m.Config.Session.Downloads.SourceSubdirectories {
|
||||||
base = filepath.Join(base, strings.Title(source))
|
base = filepath.Join(base, jsonutil.TitleCase(source))
|
||||||
}
|
}
|
||||||
fileName := naming.CleanName(title, naming.Config{
|
fileName := naming.CleanName(title, naming.Config{
|
||||||
RestrictCharacters: m.Config.Session.Filepaths.RestrictCharacters,
|
RestrictCharacters: m.Config.Session.Filepaths.RestrictCharacters,
|
||||||
@@ -1082,7 +1192,7 @@ func (m *Main) videoOutputPath(source, id, title, ext string) string {
|
|||||||
func titleFromMetadata(meta map[string]any, fallback string) string {
|
func titleFromMetadata(meta map[string]any, fallback string) string {
|
||||||
if title, ok := meta["title"].(string); ok {
|
if title, ok := meta["title"].(string); ok {
|
||||||
title = strings.TrimSpace(title)
|
title = strings.TrimSpace(title)
|
||||||
version := strings.TrimSpace(stringFromAny(meta["version"]))
|
version := strings.TrimSpace(jsonutil.StringFromAny(meta["version"]))
|
||||||
if version != "" {
|
if version != "" {
|
||||||
return title + " (" + version + ")"
|
return title + " (" + version + ")"
|
||||||
}
|
}
|
||||||
@@ -1093,70 +1203,8 @@ func titleFromMetadata(meta map[string]any, fallback string) string {
|
|||||||
return fallback
|
return fallback
|
||||||
}
|
}
|
||||||
|
|
||||||
func nestedString(v map[string]any, keys ...string) string {
|
|
||||||
return stringFromAny(nestedAny(v, keys...))
|
|
||||||
}
|
|
||||||
|
|
||||||
func nestedAny(v map[string]any, keys ...string) any {
|
|
||||||
cur := any(v)
|
|
||||||
for _, key := range keys {
|
|
||||||
m, ok := cur.(map[string]any)
|
|
||||||
if !ok {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
cur = m[key]
|
|
||||||
}
|
|
||||||
return cur
|
|
||||||
}
|
|
||||||
|
|
||||||
func stringFromAny(v any) string {
|
|
||||||
switch t := v.(type) {
|
|
||||||
case string:
|
|
||||||
return t
|
|
||||||
case float64:
|
|
||||||
return strconv.FormatFloat(t, 'f', -1, 64)
|
|
||||||
case int64:
|
|
||||||
return strconv.FormatInt(t, 10)
|
|
||||||
case int:
|
|
||||||
return strconv.Itoa(t)
|
|
||||||
default:
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func intFromAny(v any) int {
|
|
||||||
switch t := v.(type) {
|
|
||||||
case int:
|
|
||||||
return t
|
|
||||||
case int64:
|
|
||||||
return int(t)
|
|
||||||
case float64:
|
|
||||||
return int(t)
|
|
||||||
default:
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func floatFromAny(v any) float64 {
|
|
||||||
switch t := v.(type) {
|
|
||||||
case float64:
|
|
||||||
return t
|
|
||||||
case int:
|
|
||||||
return float64(t)
|
|
||||||
case int64:
|
|
||||||
return float64(t)
|
|
||||||
default:
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func boolFromAny(v any) bool {
|
|
||||||
b, _ := v.(bool)
|
|
||||||
return b
|
|
||||||
}
|
|
||||||
|
|
||||||
func replaygainGainFromAny(v any) string {
|
func replaygainGainFromAny(v any) string {
|
||||||
s := strings.TrimSpace(stringFromAny(v))
|
s := strings.TrimSpace(jsonutil.StringFromAny(v))
|
||||||
if s == "" {
|
if s == "" {
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
@@ -1177,7 +1225,7 @@ func replaygainGainFromAny(v any) string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func replaygainPeakFromAny(v any) string {
|
func replaygainPeakFromAny(v any) string {
|
||||||
return strings.TrimSpace(stringFromAny(v))
|
return strings.TrimSpace(jsonutil.StringFromAny(v))
|
||||||
}
|
}
|
||||||
|
|
||||||
func trackMetaAlbum(trackMeta map[string]any) map[string]any {
|
func trackMetaAlbum(trackMeta map[string]any) map[string]any {
|
||||||
@@ -1189,53 +1237,53 @@ func trackMetaAlbum(trackMeta map[string]any) map[string]any {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func buildTagMetadata(trackMeta map[string]any, title, source, trackID string, opts ripTrackOptions) tag.Metadata {
|
func buildTagMetadata(trackMeta map[string]any, title, source, trackID string, opts ripTrackOptions) tag.Metadata {
|
||||||
artist := nestedString(trackMeta, "performer", "name")
|
artist := jsonutil.NestedString(trackMeta, "performer", "name")
|
||||||
if artist == "" {
|
if artist == "" {
|
||||||
artist = nestedString(trackMeta, "artist", "name")
|
artist = jsonutil.NestedString(trackMeta, "artist", "name")
|
||||||
}
|
}
|
||||||
albumArtist := nestedString(trackMeta, "album", "artist", "name")
|
albumArtist := jsonutil.NestedString(trackMeta, "album", "artist", "name")
|
||||||
if albumArtist == "" {
|
if albumArtist == "" {
|
||||||
albumArtist = artist
|
albumArtist = artist
|
||||||
}
|
}
|
||||||
if strings.TrimSpace(opts.albumArtist) != "" {
|
if strings.TrimSpace(opts.albumArtist) != "" {
|
||||||
albumArtist = strings.TrimSpace(opts.albumArtist)
|
albumArtist = strings.TrimSpace(opts.albumArtist)
|
||||||
}
|
}
|
||||||
trackNumber := intFromAny(trackMeta["track_number"])
|
trackNumber := jsonutil.IntFromAny(trackMeta["track_number"])
|
||||||
if trackNumber == 0 {
|
if trackNumber == 0 {
|
||||||
trackNumber = intFromAny(trackMeta["trackNumber"])
|
trackNumber = jsonutil.IntFromAny(trackMeta["trackNumber"])
|
||||||
}
|
}
|
||||||
discNumber := intFromAny(trackMeta["media_number"])
|
discNumber := jsonutil.IntFromAny(trackMeta["media_number"])
|
||||||
if discNumber == 0 {
|
if discNumber == 0 {
|
||||||
discNumber = intFromAny(trackMeta["volumeNumber"])
|
discNumber = jsonutil.IntFromAny(trackMeta["volumeNumber"])
|
||||||
}
|
}
|
||||||
if discNumber == 0 {
|
if discNumber == 0 {
|
||||||
discNumber = intFromAny(trackMeta["disk_number"])
|
discNumber = jsonutil.IntFromAny(trackMeta["disk_number"])
|
||||||
}
|
}
|
||||||
date := stringFromAny(trackMeta["release_date_original"])
|
date := jsonutil.StringFromAny(trackMeta["release_date_original"])
|
||||||
if date == "" {
|
if date == "" {
|
||||||
date = stringFromAny(trackMeta["release_date"])
|
date = jsonutil.StringFromAny(trackMeta["release_date"])
|
||||||
}
|
}
|
||||||
if date == "" {
|
if date == "" {
|
||||||
date = stringFromAny(trackMeta["streamStartDate"])
|
date = jsonutil.StringFromAny(trackMeta["streamStartDate"])
|
||||||
}
|
}
|
||||||
album := nestedString(trackMeta, "album", "title")
|
album := jsonutil.NestedString(trackMeta, "album", "title")
|
||||||
if album == "" {
|
if album == "" {
|
||||||
album = stringFromAny(trackMeta["title"])
|
album = jsonutil.StringFromAny(trackMeta["title"])
|
||||||
}
|
}
|
||||||
trackTotal := intFromAny(trackMeta["tracks_count"])
|
trackTotal := jsonutil.IntFromAny(trackMeta["tracks_count"])
|
||||||
if trackTotal == 0 {
|
if trackTotal == 0 {
|
||||||
trackTotal = intFromAny(trackMeta["numberOfTracks"])
|
trackTotal = jsonutil.IntFromAny(trackMeta["numberOfTracks"])
|
||||||
}
|
}
|
||||||
if trackTotal == 0 {
|
if trackTotal == 0 {
|
||||||
trackTotal = intFromAny(trackMeta["track_total"])
|
trackTotal = jsonutil.IntFromAny(trackMeta["track_total"])
|
||||||
}
|
}
|
||||||
if opts.forPlaylist && opts.total > 0 {
|
if opts.forPlaylist && opts.total > 0 {
|
||||||
trackTotal = opts.total
|
trackTotal = opts.total
|
||||||
}
|
}
|
||||||
|
|
||||||
discTotal := intFromAny(trackMeta["media_count"])
|
discTotal := jsonutil.IntFromAny(trackMeta["media_count"])
|
||||||
if discTotal == 0 {
|
if discTotal == 0 {
|
||||||
discTotal = intFromAny(trackMeta["numberOfVolumes"])
|
discTotal = jsonutil.IntFromAny(trackMeta["numberOfVolumes"])
|
||||||
}
|
}
|
||||||
if discTotal == 0 && opts.albumDiscTotal > 0 {
|
if discTotal == 0 && opts.albumDiscTotal > 0 {
|
||||||
discTotal = opts.albumDiscTotal
|
discTotal = opts.albumDiscTotal
|
||||||
@@ -1247,15 +1295,15 @@ func buildTagMetadata(trackMeta map[string]any, title, source, trackID string, o
|
|||||||
discNumber = 1
|
discNumber = 1
|
||||||
}
|
}
|
||||||
|
|
||||||
genre := nestedString(trackMeta, "genre", "name")
|
genre := jsonutil.NestedString(trackMeta, "genre", "name")
|
||||||
if genre == "" {
|
if genre == "" {
|
||||||
genre = stringFromAny(trackMeta["genre"])
|
genre = jsonutil.StringFromAny(trackMeta["genre"])
|
||||||
}
|
}
|
||||||
|
|
||||||
comment := stringFromAny(trackMeta["comment"])
|
comment := jsonutil.StringFromAny(trackMeta["comment"])
|
||||||
description := stringFromAny(trackMeta["description"])
|
description := jsonutil.StringFromAny(trackMeta["description"])
|
||||||
lyrics := stringFromAny(trackMeta["lyrics"])
|
lyrics := jsonutil.StringFromAny(trackMeta["lyrics"])
|
||||||
if lrc := stringFromAny(trackMeta["lyrics_synced"]); lrc != "" {
|
if lrc := jsonutil.StringFromAny(trackMeta["lyrics_synced"]); lrc != "" {
|
||||||
lyrics = lrc
|
lyrics = lrc
|
||||||
}
|
}
|
||||||
trackGain := replaygainGainFromAny(trackMeta["replaygain_track_gain"])
|
trackGain := replaygainGainFromAny(trackMeta["replaygain_track_gain"])
|
||||||
@@ -1267,7 +1315,7 @@ func buildTagMetadata(trackMeta map[string]any, title, source, trackID string, o
|
|||||||
}
|
}
|
||||||
albumGain := replaygainGainFromAny(trackMeta["replaygain_album_gain"])
|
albumGain := replaygainGainFromAny(trackMeta["replaygain_album_gain"])
|
||||||
if albumGain == "" {
|
if albumGain == "" {
|
||||||
albumGain = replaygainGainFromAny(nestedAny(trackMeta, "album", "replaygain_album_gain"))
|
albumGain = replaygainGainFromAny(jsonutil.NestedAny(trackMeta, "album", "replaygain_album_gain"))
|
||||||
}
|
}
|
||||||
trackPeak := replaygainPeakFromAny(trackMeta["replaygain_track_peak"])
|
trackPeak := replaygainPeakFromAny(trackMeta["replaygain_track_peak"])
|
||||||
if trackPeak == "" {
|
if trackPeak == "" {
|
||||||
@@ -1275,22 +1323,22 @@ func buildTagMetadata(trackMeta map[string]any, title, source, trackID string, o
|
|||||||
}
|
}
|
||||||
albumPeak := replaygainPeakFromAny(trackMeta["replaygain_album_peak"])
|
albumPeak := replaygainPeakFromAny(trackMeta["replaygain_album_peak"])
|
||||||
if albumPeak == "" {
|
if albumPeak == "" {
|
||||||
albumPeak = replaygainPeakFromAny(nestedAny(trackMeta, "album", "replaygain_album_peak"))
|
albumPeak = replaygainPeakFromAny(jsonutil.NestedAny(trackMeta, "album", "replaygain_album_peak"))
|
||||||
}
|
}
|
||||||
|
|
||||||
sourceAlbumID := nestedString(trackMeta, "album", "id")
|
sourceAlbumID := jsonutil.NestedString(trackMeta, "album", "id")
|
||||||
if sourceAlbumID == "" {
|
if sourceAlbumID == "" {
|
||||||
sourceAlbumID = stringFromAny(trackMeta["source_album_id"])
|
sourceAlbumID = jsonutil.StringFromAny(trackMeta["source_album_id"])
|
||||||
}
|
}
|
||||||
sourceArtistID := nestedString(trackMeta, "artist", "id")
|
sourceArtistID := jsonutil.NestedString(trackMeta, "artist", "id")
|
||||||
if sourceArtistID == "" {
|
if sourceArtistID == "" {
|
||||||
sourceArtistID = nestedString(trackMeta, "performer", "id")
|
sourceArtistID = jsonutil.NestedString(trackMeta, "performer", "id")
|
||||||
}
|
}
|
||||||
if sourceArtistID == "" {
|
if sourceArtistID == "" {
|
||||||
sourceArtistID = stringFromAny(trackMeta["source_artist_id"])
|
sourceArtistID = jsonutil.StringFromAny(trackMeta["source_artist_id"])
|
||||||
}
|
}
|
||||||
sourceTrackID := trackID
|
sourceTrackID := trackID
|
||||||
if v := stringFromAny(trackMeta["source_track_id"]); v != "" {
|
if v := jsonutil.StringFromAny(trackMeta["source_track_id"]); v != "" {
|
||||||
sourceTrackID = v
|
sourceTrackID = v
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1308,8 +1356,8 @@ func buildTagMetadata(trackMeta map[string]any, title, source, trackID string, o
|
|||||||
Comment: comment,
|
Comment: comment,
|
||||||
Description: description,
|
Description: description,
|
||||||
Lyrics: lyrics,
|
Lyrics: lyrics,
|
||||||
Copyright: stringFromAny(trackMeta["copyright"]),
|
Copyright: jsonutil.StringFromAny(trackMeta["copyright"]),
|
||||||
ISRC: stringFromAny(trackMeta["isrc"]),
|
ISRC: jsonutil.StringFromAny(trackMeta["isrc"]),
|
||||||
ReplaygainTrackGain: trackGain,
|
ReplaygainTrackGain: trackGain,
|
||||||
ReplaygainAlbumGain: albumGain,
|
ReplaygainAlbumGain: albumGain,
|
||||||
ReplaygainTrackPeak: trackPeak,
|
ReplaygainTrackPeak: trackPeak,
|
||||||
@@ -1342,3 +1390,13 @@ func applyPlaylistMetadataOverrides(meta map[string]any, cfg config.MetadataConf
|
|||||||
}
|
}
|
||||||
artist["name"] = "Various Artists"
|
artist["name"] = "Various Artists"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func isFFmpegMissingError(err error) bool {
|
||||||
|
if err == nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if errors.Is(err, exec.ErrNotFound) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return strings.Contains(strings.ToLower(err.Error()), "ffmpeg not found")
|
||||||
|
}
|
||||||
|
|||||||
@@ -2,9 +2,11 @@ package app
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
"os"
|
"os"
|
||||||
|
"os/exec"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
@@ -20,6 +22,12 @@ type noopTagger struct{}
|
|||||||
|
|
||||||
func (n noopTagger) TagFLAC(string, tag.Metadata, string) error { return nil }
|
func (n noopTagger) TagFLAC(string, tag.Metadata, string) error { return nil }
|
||||||
|
|
||||||
|
type failingTagger struct {
|
||||||
|
err error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f failingTagger) TagFLAC(string, tag.Metadata, string) error { return f.err }
|
||||||
|
|
||||||
type fakeProvider struct {
|
type fakeProvider struct {
|
||||||
url string
|
url string
|
||||||
}
|
}
|
||||||
@@ -56,22 +64,34 @@ type fakeVideoProvider struct {
|
|||||||
url string
|
url string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type fakeResolvedAlbumProvider struct {
|
||||||
|
url string
|
||||||
|
downloadable provider.Downloadable
|
||||||
|
downloadableHits int
|
||||||
|
}
|
||||||
|
|
||||||
type fakeFailProvider struct{}
|
type fakeFailProvider struct{}
|
||||||
|
|
||||||
func (f *fakeAlbumProvider) Source() string { return "qobuz" }
|
func (f *fakeAlbumProvider) Source() string { return "qobuz" }
|
||||||
func (f *fakePlaylistProvider) Source() string { return "qobuz" }
|
func (f *fakePlaylistProvider) Source() string { return "qobuz" }
|
||||||
func (f *fakeVideoProvider) Source() string { return "tidal" }
|
func (f *fakeVideoProvider) Source() string { return "tidal" }
|
||||||
|
func (f *fakeResolvedAlbumProvider) Source() string { return "qobuz" }
|
||||||
func (f *fakeAlbumProvider) Login(context.Context) error { return nil }
|
func (f *fakeAlbumProvider) Login(context.Context) error { return nil }
|
||||||
func (f *fakePlaylistProvider) Login(context.Context) error {
|
func (f *fakePlaylistProvider) Login(context.Context) error {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
func (f *fakeVideoProvider) Login(context.Context) error { return nil }
|
func (f *fakeVideoProvider) Login(context.Context) error { return nil }
|
||||||
|
func (f *fakeResolvedAlbumProvider) Login(context.Context) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
func (f *fakeAlbumProvider) LoggedIn() bool { return true }
|
func (f *fakeAlbumProvider) LoggedIn() bool { return true }
|
||||||
func (f *fakePlaylistProvider) LoggedIn() bool { return true }
|
func (f *fakePlaylistProvider) LoggedIn() bool { return true }
|
||||||
func (f *fakeVideoProvider) LoggedIn() bool { return true }
|
func (f *fakeVideoProvider) LoggedIn() bool { return true }
|
||||||
|
func (f *fakeResolvedAlbumProvider) LoggedIn() bool { return true }
|
||||||
func (f *fakeAlbumProvider) Close() error { return nil }
|
func (f *fakeAlbumProvider) Close() error { return nil }
|
||||||
func (f *fakePlaylistProvider) Close() error { return nil }
|
func (f *fakePlaylistProvider) Close() error { return nil }
|
||||||
func (f *fakeVideoProvider) Close() error { return nil }
|
func (f *fakeVideoProvider) Close() error { return nil }
|
||||||
|
func (f *fakeResolvedAlbumProvider) Close() error { return nil }
|
||||||
func (f *fakeAlbumProvider) Search(context.Context, string, string, int) ([]map[string]any, error) {
|
func (f *fakeAlbumProvider) Search(context.Context, string, string, int) ([]map[string]any, error) {
|
||||||
return nil, nil
|
return nil, nil
|
||||||
}
|
}
|
||||||
@@ -81,6 +101,9 @@ func (f *fakePlaylistProvider) Search(context.Context, string, string, int) ([]m
|
|||||||
func (f *fakeVideoProvider) Search(context.Context, string, string, int) ([]map[string]any, error) {
|
func (f *fakeVideoProvider) Search(context.Context, string, string, int) ([]map[string]any, error) {
|
||||||
return nil, nil
|
return nil, nil
|
||||||
}
|
}
|
||||||
|
func (f *fakeResolvedAlbumProvider) Search(context.Context, string, string, int) ([]map[string]any, error) {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
func (f *fakeAlbumProvider) GetMetadata(_ context.Context, id string, mediaType string) (map[string]any, error) {
|
func (f *fakeAlbumProvider) GetMetadata(_ context.Context, id string, mediaType string) (map[string]any, error) {
|
||||||
if mediaType == "album" {
|
if mediaType == "album" {
|
||||||
return map[string]any{
|
return map[string]any{
|
||||||
@@ -153,6 +176,22 @@ func (f *fakeVideoProvider) GetMetadata(_ context.Context, id string, mediaType
|
|||||||
}
|
}
|
||||||
return nil, nil
|
return nil, nil
|
||||||
}
|
}
|
||||||
|
func (f *fakeResolvedAlbumProvider) GetMetadata(_ context.Context, id string, mediaType string) (map[string]any, error) {
|
||||||
|
if mediaType == "album" {
|
||||||
|
return map[string]any{
|
||||||
|
"title": "Fallback Album",
|
||||||
|
"release_date_original": "2020-01-01",
|
||||||
|
"artist": map[string]any{"name": "Fallback Artist"},
|
||||||
|
"tracks": map[string]any{"items": []any{map[string]any{"id": "t1"}}},
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
return map[string]any{
|
||||||
|
"title": "Fallback Song",
|
||||||
|
"track_number": float64(1),
|
||||||
|
"performer": map[string]any{"name": "Fallback Artist"},
|
||||||
|
"album": map[string]any{"title": "Fallback Album", "artist": map[string]any{"name": "Fallback Artist"}},
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
func (f *fakeProvider) GetDownloadable(context.Context, string, int) (*provider.Downloadable, error) {
|
func (f *fakeProvider) GetDownloadable(context.Context, string, int) (*provider.Downloadable, error) {
|
||||||
return &provider.Downloadable{URL: f.url, Extension: "flac", Source: "qobuz"}, nil
|
return &provider.Downloadable{URL: f.url, Extension: "flac", Source: "qobuz"}, nil
|
||||||
}
|
}
|
||||||
@@ -165,6 +204,14 @@ func (f *fakePlaylistProvider) GetDownloadable(context.Context, string, int) (*p
|
|||||||
func (f *fakeVideoProvider) GetDownloadable(context.Context, string, int) (*provider.Downloadable, error) {
|
func (f *fakeVideoProvider) GetDownloadable(context.Context, string, int) (*provider.Downloadable, error) {
|
||||||
return nil, nil
|
return nil, nil
|
||||||
}
|
}
|
||||||
|
func (f *fakeResolvedAlbumProvider) GetDownloadable(context.Context, string, int) (*provider.Downloadable, error) {
|
||||||
|
f.downloadableHits++
|
||||||
|
d := f.downloadable
|
||||||
|
if d.URL == "" {
|
||||||
|
d.URL = f.url
|
||||||
|
}
|
||||||
|
return &d, nil
|
||||||
|
}
|
||||||
func (f *fakeVideoProvider) GetVideoDownloadable(context.Context, string) (*provider.Downloadable, error) {
|
func (f *fakeVideoProvider) GetVideoDownloadable(context.Context, string) (*provider.Downloadable, error) {
|
||||||
return &provider.Downloadable{URL: f.url, Extension: "mp4", Source: "tidal"}, nil
|
return &provider.Downloadable{URL: f.url, Extension: "mp4", Source: "tidal"}, nil
|
||||||
}
|
}
|
||||||
@@ -237,6 +284,56 @@ func TestTrackRipPipeline(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestTrackRipFailsWhenTaggerReportsMissingFFmpeg(t *testing.T) {
|
||||||
|
tmp := t.TempDir()
|
||||||
|
|
||||||
|
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||||
|
_, _ = w.Write([]byte("audio-bytes"))
|
||||||
|
}))
|
||||||
|
defer ts.Close()
|
||||||
|
|
||||||
|
d := config.DefaultConfigData()
|
||||||
|
d.Downloads.Folder = tmp
|
||||||
|
d.Downloads.SourceSubdirectories = false
|
||||||
|
cfg := &config.Config{File: d, Session: d}
|
||||||
|
|
||||||
|
sqlite, err := store.NewSQLite(filepath.Join(tmp, "db.sqlite"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("NewSQLite() error = %v", err)
|
||||||
|
}
|
||||||
|
defer func() { _ = sqlite.Close() }()
|
||||||
|
|
||||||
|
m := &Main{
|
||||||
|
Config: cfg,
|
||||||
|
Providers: map[string]provider.Client{
|
||||||
|
"qobuz": &fakeProvider{url: ts.URL},
|
||||||
|
},
|
||||||
|
Store: sqlite,
|
||||||
|
DL: download.NewWithOptions(true, false, 0),
|
||||||
|
Tagger: failingTagger{err: fmt.Errorf("ffmpeg not found: %w", exec.ErrNotFound)},
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
if err = m.AddByID(ctx, "qobuz", "track", "19512574"); err != nil {
|
||||||
|
t.Fatalf("AddByID() error = %v", err)
|
||||||
|
}
|
||||||
|
if err = m.Resolve(ctx); err != nil {
|
||||||
|
t.Fatalf("Resolve() error = %v", err)
|
||||||
|
}
|
||||||
|
err = m.Rip(ctx)
|
||||||
|
if err == nil {
|
||||||
|
t.Fatalf("expected rip failure")
|
||||||
|
}
|
||||||
|
|
||||||
|
ok, err := sqlite.IsDownloaded(ctx, "qobuz", "19512574")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("IsDownloaded() error = %v", err)
|
||||||
|
}
|
||||||
|
if ok {
|
||||||
|
t.Fatalf("expected track not marked downloaded")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestAlbumRipPipeline(t *testing.T) {
|
func TestAlbumRipPipeline(t *testing.T) {
|
||||||
tmp := t.TempDir()
|
tmp := t.TempDir()
|
||||||
|
|
||||||
@@ -408,7 +505,7 @@ func TestTrackOutputPathFallsBackToDisc1(t *testing.T) {
|
|||||||
"performer": map[string]any{"name": "Dido"},
|
"performer": map[string]any{"name": "Dido"},
|
||||||
"album": map[string]any{"id": "a", "title": "Greatest Hits", "artist": map[string]any{"name": "Dido"}},
|
"album": map[string]any{"id": "a", "title": "Greatest Hits", "artist": map[string]any{"name": "Dido"}},
|
||||||
}
|
}
|
||||||
path := m.trackOutputPath("tidal", "1", "Song", "flac", meta, filepath.Join(tmp, "Album"), 2)
|
path := m.trackOutputPath("tidal", "1", "Song", "flac", nil, meta, filepath.Join(tmp, "Album"), 2)
|
||||||
if !strings.Contains(path, string(filepath.Separator)+"Disc 1"+string(filepath.Separator)) {
|
if !strings.Contains(path, string(filepath.Separator)+"Disc 1"+string(filepath.Separator)) {
|
||||||
t.Fatalf("expected Disc 1 subdir in path, got %q", path)
|
t.Fatalf("expected Disc 1 subdir in path, got %q", path)
|
||||||
}
|
}
|
||||||
@@ -440,7 +537,7 @@ func TestPlaylistRipPipeline(t *testing.T) {
|
|||||||
"qobuz": &fakePlaylistProvider{url: ts.URL},
|
"qobuz": &fakePlaylistProvider{url: ts.URL},
|
||||||
},
|
},
|
||||||
Store: sqlite,
|
Store: sqlite,
|
||||||
DL: download.NewWithOptions(true, false),
|
DL: download.NewWithOptions(true, false, 0),
|
||||||
Tagger: noopTagger{},
|
Tagger: noopTagger{},
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -491,7 +588,7 @@ func TestPlaylistRipUsesSourceSubdirectory(t *testing.T) {
|
|||||||
"qobuz": &fakePlaylistProvider{url: ts.URL},
|
"qobuz": &fakePlaylistProvider{url: ts.URL},
|
||||||
},
|
},
|
||||||
Store: sqlite,
|
Store: sqlite,
|
||||||
DL: download.NewWithOptions(true, false),
|
DL: download.NewWithOptions(true, false, 0),
|
||||||
Tagger: noopTagger{},
|
Tagger: noopTagger{},
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -599,12 +696,107 @@ func TestTrackOutputPathSinglesUsesAlbumID(t *testing.T) {
|
|||||||
"performer": map[string]any{"name": "Artist"},
|
"performer": map[string]any{"name": "Artist"},
|
||||||
}
|
}
|
||||||
|
|
||||||
out := m.trackOutputPath("qobuz", "track-999", "Song", "flac", meta, "", 0)
|
out := m.trackOutputPath("qobuz", "track-999", "Song", "flac", nil, meta, "", 0)
|
||||||
if got, want := filepath.Dir(out), filepath.Join(tmp, "album-123"); got != want {
|
if got, want := filepath.Dir(out), filepath.Join(tmp, "album-123"); got != want {
|
||||||
t.Fatalf("trackOutputPath() dir=%q want %q", got, want)
|
t.Fatalf("trackOutputPath() dir=%q want %q", got, want)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestTrackOutputPathSinglesUsesResolvedAudioProfile(t *testing.T) {
|
||||||
|
tmp := t.TempDir()
|
||||||
|
d := config.DefaultConfigData()
|
||||||
|
d.Downloads.Folder = tmp
|
||||||
|
d.Downloads.SourceSubdirectories = false
|
||||||
|
d.Filepaths.AddSinglesToFolder = true
|
||||||
|
d.Filepaths.FolderFormat = "{container}-{bit_depth}-{sampling_rate}"
|
||||||
|
d.Filepaths.TrackFormat = "{title}"
|
||||||
|
d.Filepaths.RestrictCharacters = false
|
||||||
|
|
||||||
|
m := &Main{Config: &config.Config{File: d, Session: d}}
|
||||||
|
meta := map[string]any{
|
||||||
|
"album": map[string]any{
|
||||||
|
"id": "album-123",
|
||||||
|
"title": "Album",
|
||||||
|
"artist": map[string]any{"name": "Artist"},
|
||||||
|
},
|
||||||
|
"performer": map[string]any{"name": "Artist"},
|
||||||
|
}
|
||||||
|
dl := &provider.Downloadable{Extension: "mp3", Audio: provider.AudioProfile{Container: "MP3", Codec: "MP3", Quality: "HIGH", BitDepth: 16, SamplingRate: "44.1", BitrateKbps: 320}}
|
||||||
|
|
||||||
|
out := m.trackOutputPath("qobuz", "track-999", "Song", "mp3", dl, meta, "", 0)
|
||||||
|
if got, want := filepath.Dir(out), filepath.Join(tmp, "MP3-16-44.1"); got != want {
|
||||||
|
t.Fatalf("trackOutputPath() dir=%q want %q", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRipAlbumUsesResolvedAudioProfileForFolderName(t *testing.T) {
|
||||||
|
tmp := t.TempDir()
|
||||||
|
|
||||||
|
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||||
|
_, _ = w.Write([]byte("audio-bytes"))
|
||||||
|
}))
|
||||||
|
defer ts.Close()
|
||||||
|
|
||||||
|
d := config.DefaultConfigData()
|
||||||
|
d.Downloads.Folder = tmp
|
||||||
|
d.Downloads.SourceSubdirectories = false
|
||||||
|
d.Downloads.Concurrency = false
|
||||||
|
d.Filepaths.RestrictCharacters = false
|
||||||
|
cfg := &config.Config{File: d, Session: d}
|
||||||
|
|
||||||
|
sqlite, err := store.NewSQLite(filepath.Join(tmp, "db.sqlite"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("NewSQLite() error = %v", err)
|
||||||
|
}
|
||||||
|
defer func() { _ = sqlite.Close() }()
|
||||||
|
|
||||||
|
fake := &fakeResolvedAlbumProvider{
|
||||||
|
url: ts.URL,
|
||||||
|
downloadable: provider.Downloadable{
|
||||||
|
URL: ts.URL,
|
||||||
|
Extension: "mp3",
|
||||||
|
Source: "qobuz",
|
||||||
|
Audio: provider.AudioProfile{
|
||||||
|
Container: "MP3",
|
||||||
|
Codec: "MP3",
|
||||||
|
Quality: "HIGH",
|
||||||
|
BitDepth: 16,
|
||||||
|
SamplingRate: "44.1",
|
||||||
|
BitrateKbps: 320,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
m := &Main{
|
||||||
|
Config: cfg,
|
||||||
|
Providers: map[string]provider.Client{
|
||||||
|
"qobuz": fake,
|
||||||
|
},
|
||||||
|
Store: sqlite,
|
||||||
|
DL: download.NewWithOptions(true, false, 0),
|
||||||
|
Tagger: noopTagger{},
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
if err = m.AddByID(ctx, "qobuz", "album", "a1"); err != nil {
|
||||||
|
t.Fatalf("AddByID() error = %v", err)
|
||||||
|
}
|
||||||
|
if err = m.Resolve(ctx); err != nil {
|
||||||
|
t.Fatalf("Resolve() error = %v", err)
|
||||||
|
}
|
||||||
|
if err = m.Rip(ctx); err != nil {
|
||||||
|
t.Fatalf("Rip() error = %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
folder := filepath.Join(tmp, "Fallback Artist - Fallback Album (2020) [MP3] [16B-44.1kHz]")
|
||||||
|
if _, err = os.Stat(filepath.Join(folder, "01. Fallback Artist - Fallback Song.mp3")); err != nil {
|
||||||
|
t.Fatalf("missing track in resolved-quality folder: %v", err)
|
||||||
|
}
|
||||||
|
if fake.downloadableHits != 1 {
|
||||||
|
t.Fatalf("GetDownloadable() calls=%d, want 1 (prefetched reuse)", fake.downloadableHits)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestBuildTagMetadataReplayGainFallbacks(t *testing.T) {
|
func TestBuildTagMetadataReplayGainFallbacks(t *testing.T) {
|
||||||
meta := map[string]any{
|
meta := map[string]any{
|
||||||
"replayGain": float64(-7.25),
|
"replayGain": float64(-7.25),
|
||||||
|
|||||||
@@ -52,13 +52,13 @@ func Convert(path string, cfg config.ConversionConfig) (string, error) {
|
|||||||
return path, fmt.Errorf("conversion failed: %w: %s", err, string(output))
|
return path, fmt.Errorf("conversion failed: %w: %s", err, string(output))
|
||||||
}
|
}
|
||||||
|
|
||||||
if path != finalPath {
|
|
||||||
_ = os.Remove(path)
|
|
||||||
}
|
|
||||||
if err = os.Rename(tmpPath, finalPath); err != nil {
|
if err = os.Rename(tmpPath, finalPath); err != nil {
|
||||||
_ = os.Remove(tmpPath)
|
_ = os.Remove(tmpPath)
|
||||||
return path, err
|
return path, err
|
||||||
}
|
}
|
||||||
|
if path != finalPath {
|
||||||
|
_ = os.Remove(path)
|
||||||
|
}
|
||||||
|
|
||||||
return finalPath, nil
|
return finalPath, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
package convert
|
package convert
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
@@ -59,3 +61,43 @@ func TestBuildFFmpegArgsNoCoverForOpus(t *testing.T) {
|
|||||||
t.Fatalf("unexpected cover map args=%s", joined)
|
t.Fatalf("unexpected cover map args=%s", joined)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestConvertKeepsSourceWhenRenameFails(t *testing.T) {
|
||||||
|
tmp := t.TempDir()
|
||||||
|
in := filepath.Join(tmp, "song.flac")
|
||||||
|
if err := os.WriteFile(in, []byte("src"), 0o644); err != nil {
|
||||||
|
t.Fatalf("write input: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
fakeBin := filepath.Join(tmp, "bin")
|
||||||
|
if err := os.MkdirAll(fakeBin, 0o755); err != nil {
|
||||||
|
t.Fatalf("mkdir bin: %v", err)
|
||||||
|
}
|
||||||
|
fakeFFmpeg := filepath.Join(fakeBin, "ffmpeg")
|
||||||
|
script := "#!/bin/sh\nout=\"\"\nfor arg in \"$@\"; do out=\"$arg\"; done\n: > \"$out\"\n"
|
||||||
|
if err := os.WriteFile(fakeFFmpeg, []byte(script), 0o755); err != nil {
|
||||||
|
t.Fatalf("write fake ffmpeg: %v", err)
|
||||||
|
}
|
||||||
|
t.Setenv("PATH", fakeBin)
|
||||||
|
|
||||||
|
finalPath := strings.TrimSuffix(in, filepath.Ext(in)) + ".m4a"
|
||||||
|
if err := os.Mkdir(finalPath, 0o755); err != nil {
|
||||||
|
t.Fatalf("mkdir final path: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
cfg := config.ConversionConfig{Enabled: true, Codec: "ALAC"}
|
||||||
|
out, err := Convert(in, cfg)
|
||||||
|
if err == nil {
|
||||||
|
t.Fatalf("expected rename failure")
|
||||||
|
}
|
||||||
|
if out != in {
|
||||||
|
t.Fatalf("returned path = %q, want %q", out, in)
|
||||||
|
}
|
||||||
|
if _, statErr := os.Stat(in); statErr != nil {
|
||||||
|
t.Fatalf("expected source to remain, stat err=%v", statErr)
|
||||||
|
}
|
||||||
|
tmpPath := finalPath + ".tmp.m4a"
|
||||||
|
if _, statErr := os.Stat(tmpPath); !os.IsNotExist(statErr) {
|
||||||
|
t.Fatalf("expected temp output cleanup, stat err=%v", statErr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -14,7 +14,6 @@ import (
|
|||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"sync/atomic"
|
"sync/atomic"
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/vbauerster/mpb/v8"
|
"github.com/vbauerster/mpb/v8"
|
||||||
"github.com/vbauerster/mpb/v8/decor"
|
"github.com/vbauerster/mpb/v8/decor"
|
||||||
@@ -32,18 +31,23 @@ type Downloader struct {
|
|||||||
barStarted atomic.Int32
|
barStarted atomic.Int32
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// downloadBufferSize sizes HTTP-to-disk copies. 1 MiB cuts read/write syscalls
|
||||||
|
// ~32x vs Go's default 32 KiB io.Copy buffer, which matters for multi-MB FLAC
|
||||||
|
// streams off CDNs that can sustain high per-connection throughput.
|
||||||
|
const downloadBufferSize = 1 << 20
|
||||||
|
|
||||||
func New() *Downloader {
|
func New() *Downloader {
|
||||||
return NewWithOptions(true, true)
|
return NewWithOptions(true, true, 0)
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewWithVerifySSL(verifySSL bool) *Downloader {
|
func NewWithVerifySSL(verifySSL bool) *Downloader {
|
||||||
return NewWithOptions(verifySSL, true)
|
return NewWithOptions(verifySSL, true, 0)
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewWithOptions(verifySSL bool, showProgress bool) *Downloader {
|
func NewWithOptions(verifySSL bool, showProgress bool, maxConnsPerHost int) *Downloader {
|
||||||
forceProgress := strings.EqualFold(os.Getenv("STREAMRIP_GO_FORCE_PROGRESS"), "1") || strings.EqualFold(os.Getenv("STREAMRIP_GO_FORCE_PROGRESS"), "true")
|
forceProgress := strings.EqualFold(os.Getenv("STREAMRIP_GO_FORCE_PROGRESS"), "1") || strings.EqualFold(os.Getenv("STREAMRIP_GO_FORCE_PROGRESS"), "true")
|
||||||
interactive := showProgress && (forceProgress || (term.IsTerminal(int(os.Stderr.Fd())) && strings.ToLower(os.Getenv("TERM")) != "dumb"))
|
interactive := showProgress && (forceProgress || (term.IsTerminal(int(os.Stderr.Fd())) && strings.ToLower(os.Getenv("TERM")) != "dumb"))
|
||||||
d := &Downloader{http: netutil.NewHTTPClient(0, verifySSL), showProgress: interactive}
|
d := &Downloader{http: netutil.NewHTTPClient(0, verifySSL, maxConnsPerHost), showProgress: interactive}
|
||||||
if interactive {
|
if interactive {
|
||||||
d.progress = mpb.New(mpb.WithWidth(40), mpb.WithOutput(os.Stderr))
|
d.progress = mpb.New(mpb.WithWidth(40), mpb.WithOutput(os.Stderr))
|
||||||
}
|
}
|
||||||
@@ -125,6 +129,11 @@ func (d *Downloader) FileDeezerEncrypted(ctx context.Context, sourceURL, outputP
|
|||||||
)
|
)
|
||||||
defer bar.SetTotal(-1, true)
|
defer bar.SetTotal(-1, true)
|
||||||
}
|
}
|
||||||
|
defer func() {
|
||||||
|
if !success && bar != nil {
|
||||||
|
bar.Abort(true)
|
||||||
|
}
|
||||||
|
}()
|
||||||
}
|
}
|
||||||
|
|
||||||
block, err := blowfish.NewCipher(deriveDeezerBlowfishKey(trackID))
|
block, err := blowfish.NewCipher(deriveDeezerBlowfishKey(trackID))
|
||||||
@@ -245,7 +254,12 @@ func (d *Downloader) file(ctx context.Context, sourceURL, outputPath string, all
|
|||||||
)
|
)
|
||||||
defer bar.SetTotal(-1, true)
|
defer bar.SetTotal(-1, true)
|
||||||
}
|
}
|
||||||
buf := make([]byte, 256*1024)
|
defer func() {
|
||||||
|
if !success && bar != nil {
|
||||||
|
bar.Abort(true)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
buf := make([]byte, downloadBufferSize)
|
||||||
totalWritten := int64(0)
|
totalWritten := int64(0)
|
||||||
for {
|
for {
|
||||||
n, readErr := reader.Read(buf)
|
n, readErr := reader.Read(buf)
|
||||||
@@ -270,7 +284,7 @@ func (d *Downloader) file(ctx context.Context, sourceURL, outputPath string, all
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
written, copyErr := io.Copy(out, reader)
|
written, copyErr := io.CopyBuffer(out, reader, make([]byte, downloadBufferSize))
|
||||||
if copyErr != nil {
|
if copyErr != nil {
|
||||||
return copyErr
|
return copyErr
|
||||||
}
|
}
|
||||||
@@ -320,57 +334,13 @@ func shortenName(name string, max int) string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (d *Downloader) streamManifestWithFFmpeg(ctx context.Context, sourceURL, outputPath string, includeVideo bool) error {
|
func (d *Downloader) streamManifestWithFFmpeg(ctx context.Context, sourceURL, outputPath string, includeVideo bool) error {
|
||||||
stopSpinner := func() {}
|
|
||||||
if d.ProgressEnabled() {
|
|
||||||
d.barStarted.Store(1)
|
|
||||||
desc := shortenName(filepath.Base(outputPath), 54)
|
|
||||||
spin := d.progress.AddSpinner(
|
|
||||||
0,
|
|
||||||
mpb.PrependDecorators(
|
|
||||||
decor.Name(desc+" ", decor.WC{W: 56, C: decor.DSyncWidth | decor.DindentRight}),
|
|
||||||
),
|
|
||||||
mpb.AppendDecorators(
|
|
||||||
decor.Elapsed(decor.ET_STYLE_GO, decor.WCSyncWidthR),
|
|
||||||
decor.Name(" | ffmpeg stream", decor.WCSyncWidth),
|
|
||||||
),
|
|
||||||
mpb.BarRemoveOnComplete(),
|
|
||||||
)
|
|
||||||
done := make(chan struct{})
|
|
||||||
go func() {
|
|
||||||
ticker := time.NewTicker(120 * time.Millisecond)
|
|
||||||
defer ticker.Stop()
|
|
||||||
for {
|
|
||||||
select {
|
|
||||||
case <-ticker.C:
|
|
||||||
spin.IncrBy(1)
|
|
||||||
case <-done:
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
stopSpinner = func() {
|
|
||||||
close(done)
|
|
||||||
spin.SetTotal(-1, true)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
defer stopSpinner()
|
|
||||||
|
|
||||||
if _, err := exec.LookPath("ffmpeg"); err != nil {
|
if _, err := exec.LookPath("ffmpeg"); err != nil {
|
||||||
return fmt.Errorf("ffmpeg not found for manifest stream: %w", err)
|
return fmt.Errorf("ffmpeg not found for manifest stream: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
args := []string{
|
args := buildFFmpegStreamArgs(sourceURL, outputPath, includeVideo)
|
||||||
"-y",
|
|
||||||
"-protocol_whitelist", "file,http,https,tcp,tls,crypto,data",
|
|
||||||
"-i", sourceURL,
|
|
||||||
}
|
|
||||||
if includeVideo {
|
|
||||||
args = append(args, "-map", "0")
|
|
||||||
} else {
|
|
||||||
args = append(args, "-map", "0:a:0")
|
|
||||||
}
|
|
||||||
args = append(args, "-c", "copy", outputPath)
|
|
||||||
|
|
||||||
|
if !d.ProgressEnabled() {
|
||||||
cmd := exec.CommandContext(ctx, "ffmpeg", args...)
|
cmd := exec.CommandContext(ctx, "ffmpeg", args...)
|
||||||
output, err := cmd.CombinedOutput()
|
output, err := cmd.CombinedOutput()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -378,6 +348,169 @@ func (d *Downloader) streamManifestWithFFmpeg(ctx context.Context, sourceURL, ou
|
|||||||
return fmt.Errorf("ffmpeg stream copy failed: %w: %s", err, string(output))
|
return fmt.Errorf("ffmpeg stream copy failed: %w: %s", err, string(output))
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
d.barStarted.Store(1)
|
||||||
|
desc := shortenName(filepath.Base(outputPath), 54)
|
||||||
|
spinner := d.progress.AddSpinner(
|
||||||
|
0,
|
||||||
|
mpb.PrependDecorators(
|
||||||
|
decor.Name(desc+" ", decor.WC{W: 56, C: decor.DSyncWidth | decor.DindentRight}),
|
||||||
|
),
|
||||||
|
mpb.AppendDecorators(
|
||||||
|
decor.CurrentKibiByte("% .1f", decor.WCSyncWidthR),
|
||||||
|
decor.Name(" | ", decor.WCSyncWidth),
|
||||||
|
decor.Elapsed(decor.ET_STYLE_GO, decor.WCSyncWidthR),
|
||||||
|
),
|
||||||
|
mpb.BarRemoveOnComplete(),
|
||||||
|
)
|
||||||
|
|
||||||
|
cmd := exec.CommandContext(ctx, "ffmpeg", args...)
|
||||||
|
stderr, err := cmd.StderrPipe()
|
||||||
|
if err != nil {
|
||||||
|
spinner.SetTotal(-1, true)
|
||||||
|
return fmt.Errorf("ffmpeg stream setup failed: %w", err)
|
||||||
|
}
|
||||||
|
if err = cmd.Start(); err != nil {
|
||||||
|
spinner.SetTotal(-1, true)
|
||||||
|
return fmt.Errorf("ffmpeg stream setup failed: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var ffOut strings.Builder
|
||||||
|
scanDone := make(chan scanState, 1)
|
||||||
|
go func() {
|
||||||
|
state := scanState{}
|
||||||
|
shownBytes := int64(0)
|
||||||
|
barTotalBytes := int64(0)
|
||||||
|
newEstimatedBar := func(totalBytes int64) *mpb.Bar {
|
||||||
|
return d.progress.AddBar(
|
||||||
|
totalBytes,
|
||||||
|
mpb.PrependDecorators(
|
||||||
|
decor.Name(desc+" ", decor.WC{W: 56, C: decor.DSyncWidth | decor.DindentRight}),
|
||||||
|
decor.Percentage(decor.WCSyncWidthR),
|
||||||
|
),
|
||||||
|
mpb.AppendDecorators(
|
||||||
|
decor.CountersKibiByte("% .1f / % .1f", decor.WCSyncWidthR),
|
||||||
|
decor.Name(" | ", decor.WCSyncWidth),
|
||||||
|
decor.AverageSpeed(decor.SizeB1024(0), "% .1f", decor.WCSyncWidthR),
|
||||||
|
decor.Name(" | ETA ", decor.WCSyncWidth),
|
||||||
|
decor.AverageETA(decor.ET_STYLE_GO, decor.WCSyncWidthR),
|
||||||
|
),
|
||||||
|
mpb.BarRemoveOnComplete(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
var bar *mpb.Bar
|
||||||
|
scanner := bufio.NewScanner(stderr)
|
||||||
|
scanner.Buffer(make([]byte, 0, 64*1024), 1024*1024)
|
||||||
|
for scanner.Scan() {
|
||||||
|
line := scanner.Text()
|
||||||
|
if ffOut.Len() < 256*1024 {
|
||||||
|
ffOut.WriteString(line)
|
||||||
|
ffOut.WriteByte('\n')
|
||||||
|
}
|
||||||
|
if totalMS, ok := parseFFmpegDurationLine(line); ok && totalMS > 0 {
|
||||||
|
state.totalMS = totalMS
|
||||||
|
}
|
||||||
|
if bitrateBPS, ok := parseFFmpegDurationBitrateBPS(line); ok && bitrateBPS > 0 {
|
||||||
|
state.bitrateBPS = bitrateBPS
|
||||||
|
}
|
||||||
|
if bitrateBPS, ok := parseFFmpegProgressBitrateBPS(line); ok && bitrateBPS > 0 {
|
||||||
|
state.bitrateBPS = bitrateBPS
|
||||||
|
}
|
||||||
|
if totalSize, ok := parseFFmpegTotalSize(line); ok && totalSize > state.currentBytes {
|
||||||
|
state.currentBytes = totalSize
|
||||||
|
}
|
||||||
|
if currentMS, ok := parseFFmpegOutTime(line); ok {
|
||||||
|
if currentMS > state.currentMS {
|
||||||
|
state.currentMS = currentMS
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if bar == nil {
|
||||||
|
estimatedTotal := int64(0)
|
||||||
|
if state.totalMS > 0 && state.bitrateBPS > 0 {
|
||||||
|
estimatedTotal = estimateTotalBytesFromBitrate(state.totalMS, state.bitrateBPS)
|
||||||
|
}
|
||||||
|
if estimatedTotal == 0 {
|
||||||
|
estimatedTotal = estimateTotalBytesFromProgress(state.totalMS, state.currentMS, state.currentBytes)
|
||||||
|
}
|
||||||
|
if estimatedTotal > 0 {
|
||||||
|
if estimatedTotal < state.currentBytes {
|
||||||
|
estimatedTotal = state.currentBytes
|
||||||
|
}
|
||||||
|
barTotalBytes = estimatedTotal
|
||||||
|
spinner.SetTotal(-1, true)
|
||||||
|
bar = newEstimatedBar(barTotalBytes)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if state.currentBytes > shownBytes {
|
||||||
|
delta := state.currentBytes - shownBytes
|
||||||
|
if bar != nil {
|
||||||
|
bar.IncrBy(int(delta))
|
||||||
|
if state.currentBytes > barTotalBytes {
|
||||||
|
barTotalBytes = state.currentBytes
|
||||||
|
bar.SetTotal(barTotalBytes, false)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
spinner.IncrBy(int(delta))
|
||||||
|
}
|
||||||
|
shownBytes = state.currentBytes
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if bar != nil {
|
||||||
|
if shownBytes < barTotalBytes {
|
||||||
|
bar.IncrBy(int(barTotalBytes - shownBytes))
|
||||||
|
}
|
||||||
|
bar.SetTotal(barTotalBytes, true)
|
||||||
|
} else {
|
||||||
|
spinner.SetTotal(-1, true)
|
||||||
|
}
|
||||||
|
state.currentBytes = shownBytes
|
||||||
|
state.scanErr = scanner.Err()
|
||||||
|
scanDone <- state
|
||||||
|
}()
|
||||||
|
|
||||||
|
waitErr := cmd.Wait()
|
||||||
|
state := <-scanDone
|
||||||
|
|
||||||
|
if waitErr != nil {
|
||||||
|
_ = os.Remove(outputPath)
|
||||||
|
if out := strings.TrimSpace(ffOut.String()); out != "" {
|
||||||
|
return fmt.Errorf("ffmpeg stream copy failed: %w: %s", waitErr, out)
|
||||||
|
}
|
||||||
|
return fmt.Errorf("ffmpeg stream copy failed: %w", waitErr)
|
||||||
|
}
|
||||||
|
if state.scanErr != nil {
|
||||||
|
return fmt.Errorf("ffmpeg stream output read failed: %w", state.scanErr)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func buildFFmpegStreamArgs(sourceURL, outputPath string, includeVideo bool) []string {
|
||||||
|
args := []string{
|
||||||
|
"-y",
|
||||||
|
"-protocol_whitelist", "file,http,https,tcp,tls,crypto,data",
|
||||||
|
"-i", sourceURL,
|
||||||
|
}
|
||||||
|
if includeVideo {
|
||||||
|
args = append(args,
|
||||||
|
"-map", "0:v:0?",
|
||||||
|
"-map", "0:a:0?",
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
args = append(args, "-map", "0:a:0")
|
||||||
|
}
|
||||||
|
args = append(args, "-c", "copy", "-hide_banner", "-nostats", "-progress", "pipe:2", outputPath)
|
||||||
|
return args
|
||||||
|
}
|
||||||
|
|
||||||
|
type scanState struct {
|
||||||
|
totalMS int64
|
||||||
|
currentMS int64
|
||||||
|
bitrateBPS int64
|
||||||
|
currentBytes int64
|
||||||
|
scanErr error
|
||||||
}
|
}
|
||||||
|
|
||||||
func isManifestResponse(contentType string, peek []byte) bool {
|
func isManifestResponse(contentType string, peek []byte) bool {
|
||||||
@@ -395,35 +528,184 @@ func isManifestResponse(contentType string, peek []byte) bool {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func parseFFmpegDurationLine(line string) (int64, bool) {
|
||||||
|
idx := strings.Index(line, "Duration:")
|
||||||
|
if idx < 0 {
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
raw := strings.TrimSpace(line[idx+len("Duration:"):])
|
||||||
|
if raw == "" {
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
if comma := strings.Index(raw, ","); comma >= 0 {
|
||||||
|
raw = raw[:comma]
|
||||||
|
}
|
||||||
|
return parseClockDurationMS(raw)
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseFFmpegOutTime(line string) (int64, bool) {
|
||||||
|
if !strings.HasPrefix(line, "out_time=") {
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
raw := strings.TrimSpace(strings.TrimPrefix(line, "out_time="))
|
||||||
|
if raw == "" || strings.EqualFold(raw, "N/A") {
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
return parseClockDurationMS(raw)
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseFFmpegTotalSize(line string) (int64, bool) {
|
||||||
|
if !strings.HasPrefix(line, "total_size=") {
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
raw := strings.TrimSpace(strings.TrimPrefix(line, "total_size="))
|
||||||
|
if raw == "" || strings.EqualFold(raw, "N/A") {
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
v, err := strconv.ParseInt(raw, 10, 64)
|
||||||
|
if err != nil || v < 0 {
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
return v, true
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseFFmpegDurationBitrateBPS(line string) (int64, bool) {
|
||||||
|
idx := strings.Index(strings.ToLower(line), "bitrate:")
|
||||||
|
if idx < 0 {
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
raw := strings.TrimSpace(line[idx+len("bitrate:"):])
|
||||||
|
if raw == "" {
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
return parseFFmpegBitrateBPS(raw)
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseFFmpegProgressBitrateBPS(line string) (int64, bool) {
|
||||||
|
if !strings.HasPrefix(line, "bitrate=") {
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
raw := strings.TrimSpace(strings.TrimPrefix(line, "bitrate="))
|
||||||
|
if raw == "" || strings.EqualFold(raw, "N/A") {
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
return parseFFmpegBitrateBPS(raw)
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseFFmpegBitrateBPS(raw string) (int64, bool) {
|
||||||
|
raw = strings.TrimSpace(raw)
|
||||||
|
if raw == "" || strings.EqualFold(raw, "N/A") {
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
parts := strings.Fields(strings.ToLower(raw))
|
||||||
|
if len(parts) == 0 {
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
numStr := parts[0]
|
||||||
|
unit := ""
|
||||||
|
if len(parts) > 1 {
|
||||||
|
unit = parts[1]
|
||||||
|
} else {
|
||||||
|
i := 0
|
||||||
|
for i < len(numStr) {
|
||||||
|
c := numStr[i]
|
||||||
|
if (c >= '0' && c <= '9') || c == '.' {
|
||||||
|
i++
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if i < len(numStr) {
|
||||||
|
unit = numStr[i:]
|
||||||
|
numStr = numStr[:i]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
num, err := strconv.ParseFloat(strings.TrimSpace(numStr), 64)
|
||||||
|
if err != nil || num <= 0 {
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
unit = strings.TrimSpace(strings.Trim(unit, ","))
|
||||||
|
mult := float64(1)
|
||||||
|
switch unit {
|
||||||
|
case "kb/s", "kbits/s", "kbit/s", "kbps":
|
||||||
|
mult = 1000
|
||||||
|
case "mb/s", "mbits/s", "mbit/s", "mbps":
|
||||||
|
mult = 1000 * 1000
|
||||||
|
case "gb/s", "gbits/s", "gbit/s", "gbps":
|
||||||
|
mult = 1000 * 1000 * 1000
|
||||||
|
case "b/s", "bit/s", "bits/s", "":
|
||||||
|
mult = 1
|
||||||
|
default:
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
bps := int64(num * mult)
|
||||||
|
if bps <= 0 {
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
return bps, true
|
||||||
|
}
|
||||||
|
|
||||||
|
func estimateTotalBytesFromBitrate(totalMS, bitrateBPS int64) int64 {
|
||||||
|
if totalMS <= 0 || bitrateBPS <= 0 {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
return (totalMS * bitrateBPS) / 8000
|
||||||
|
}
|
||||||
|
|
||||||
|
func estimateTotalBytesFromProgress(totalMS, currentMS, currentBytes int64) int64 {
|
||||||
|
if totalMS <= 0 || currentMS <= 0 || currentBytes <= 0 {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
if currentMS > totalMS {
|
||||||
|
currentMS = totalMS
|
||||||
|
}
|
||||||
|
est := (currentBytes * totalMS) / currentMS
|
||||||
|
if est < currentBytes {
|
||||||
|
est = currentBytes
|
||||||
|
}
|
||||||
|
return est
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseClockDurationMS(raw string) (int64, bool) {
|
||||||
|
parts := strings.Split(strings.TrimSpace(raw), ":")
|
||||||
|
if len(parts) != 3 {
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
hours, err := strconv.ParseInt(parts[0], 10, 64)
|
||||||
|
if err != nil || hours < 0 {
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
minutes, err := strconv.ParseInt(parts[1], 10, 64)
|
||||||
|
if err != nil || minutes < 0 {
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
secPart := parts[2]
|
||||||
|
secRaw, fracRaw, hasFrac := strings.Cut(secPart, ".")
|
||||||
|
seconds, err := strconv.ParseInt(secRaw, 10, 64)
|
||||||
|
if err != nil || seconds < 0 {
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
ms := ((hours*60+minutes)*60 + seconds) * 1000
|
||||||
|
if hasFrac {
|
||||||
|
if len(fracRaw) > 3 {
|
||||||
|
fracRaw = fracRaw[:3]
|
||||||
|
}
|
||||||
|
for len(fracRaw) < 3 {
|
||||||
|
fracRaw += "0"
|
||||||
|
}
|
||||||
|
fracMS, fracErr := strconv.ParseInt(fracRaw, 10, 64)
|
||||||
|
if fracErr != nil || fracMS < 0 {
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
ms += fracMS
|
||||||
|
}
|
||||||
|
return ms, true
|
||||||
|
}
|
||||||
|
|
||||||
const deezerBFChunkSize = 2048
|
const deezerBFChunkSize = 2048
|
||||||
|
|
||||||
var deezerBFIV = []byte{0, 1, 2, 3, 4, 5, 6, 7}
|
var deezerBFIV = []byte{0, 1, 2, 3, 4, 5, 6, 7}
|
||||||
|
|
||||||
func decryptDeezerBFCBCStripe(in []byte, trackID string) ([]byte, error) {
|
|
||||||
block, err := blowfish.NewCipher(deriveDeezerBlowfishKey(trackID))
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
out := make([]byte, len(in))
|
|
||||||
for i := 0; i*deezerBFChunkSize < len(in); i++ {
|
|
||||||
start := i * deezerBFChunkSize
|
|
||||||
end := start + deezerBFChunkSize
|
|
||||||
if end > len(in) {
|
|
||||||
end = len(in)
|
|
||||||
}
|
|
||||||
chunk := in[start:end]
|
|
||||||
if i%3 == 0 && len(chunk) == deezerBFChunkSize {
|
|
||||||
dec := make([]byte, len(chunk))
|
|
||||||
mode := cipher.NewCBCDecrypter(block, deezerBFIV)
|
|
||||||
mode.CryptBlocks(dec, chunk)
|
|
||||||
copy(out[start:end], dec)
|
|
||||||
} else {
|
|
||||||
copy(out[start:end], chunk)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return out, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func deriveDeezerBlowfishKey(trackID string) []byte {
|
func deriveDeezerBlowfishKey(trackID string) []byte {
|
||||||
sum := md5.Sum([]byte(trackID))
|
sum := md5.Sum([]byte(trackID))
|
||||||
md5Hex := fmt.Sprintf("%x", sum)
|
md5Hex := fmt.Sprintf("%x", sum)
|
||||||
@@ -434,20 +716,3 @@ func deriveDeezerBlowfishKey(trackID string) []byte {
|
|||||||
}
|
}
|
||||||
return key
|
return key
|
||||||
}
|
}
|
||||||
|
|
||||||
func normalizeDeezerTrackID(raw string) string {
|
|
||||||
trimmed := strings.TrimSpace(raw)
|
|
||||||
if trimmed == "" {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
if _, err := strconv.Atoi(trimmed); err == nil {
|
|
||||||
return trimmed
|
|
||||||
}
|
|
||||||
parts := strings.Split(strings.Trim(trimmed, "/"), "/")
|
|
||||||
for i := len(parts) - 1; i >= 0; i-- {
|
|
||||||
if _, err := strconv.Atoi(parts[i]); err == nil {
|
|
||||||
return parts[i]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return trimmed
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func TestDownloaderHasNoClientTimeout(t *testing.T) {
|
func TestDownloaderHasNoClientTimeout(t *testing.T) {
|
||||||
d := NewWithOptions(true, false)
|
d := NewWithOptions(true, false, 0)
|
||||||
if d.http.Timeout != 0 {
|
if d.http.Timeout != 0 {
|
||||||
t.Fatalf("http timeout = %v, want 0 (no global timeout)", d.http.Timeout)
|
t.Fatalf("http timeout = %v, want 0 (no global timeout)", d.http.Timeout)
|
||||||
}
|
}
|
||||||
@@ -66,33 +66,11 @@ func TestManifestDetection(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestNormalizeDeezerTrackID(t *testing.T) {
|
func TestDeezerBlowfishKeyDerivation(t *testing.T) {
|
||||||
if got := normalizeDeezerTrackID("https://www.deezer.com/track/3135556"); got != "3135556" {
|
|
||||||
t.Fatalf("normalize track id = %q, want 3135556", got)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestDecryptDeezerBFCBCStripe(t *testing.T) {
|
|
||||||
trackID := "3135556"
|
trackID := "3135556"
|
||||||
plain := make([]byte, deezerBFChunkSize*2)
|
key := deriveDeezerBlowfishKey(trackID)
|
||||||
for i := range plain {
|
if len(key) != 16 {
|
||||||
plain[i] = byte(i % 251)
|
t.Fatalf("blowfish key len = %d, want 16", len(key))
|
||||||
}
|
|
||||||
enc := make([]byte, len(plain))
|
|
||||||
copy(enc, plain)
|
|
||||||
block, err := blowfish.NewCipher(deriveDeezerBlowfishKey(trackID))
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("cipher error: %v", err)
|
|
||||||
}
|
|
||||||
cbc := cipher.NewCBCEncrypter(block, deezerBFIV)
|
|
||||||
cbc.CryptBlocks(enc[:deezerBFChunkSize], enc[:deezerBFChunkSize])
|
|
||||||
|
|
||||||
dec, err := decryptDeezerBFCBCStripe(enc, trackID)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("decrypt error: %v", err)
|
|
||||||
}
|
|
||||||
if len(dec) != len(plain) || string(dec) != string(plain) {
|
|
||||||
t.Fatalf("decrypted data mismatch")
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -117,7 +95,7 @@ func TestFileDeezerEncrypted(t *testing.T) {
|
|||||||
}))
|
}))
|
||||||
defer ts.Close()
|
defer ts.Close()
|
||||||
|
|
||||||
d := NewWithOptions(true, false)
|
d := NewWithOptions(true, false, 0)
|
||||||
out := filepath.Join(t.TempDir(), "x", "a.flac")
|
out := filepath.Join(t.TempDir(), "x", "a.flac")
|
||||||
if err = d.FileDeezerEncrypted(context.Background(), ts.URL, out, trackID); err != nil {
|
if err = d.FileDeezerEncrypted(context.Background(), ts.URL, out, trackID); err != nil {
|
||||||
t.Fatalf("FileDeezerEncrypted() error = %v", err)
|
t.Fatalf("FileDeezerEncrypted() error = %v", err)
|
||||||
@@ -139,7 +117,7 @@ func TestDownloaderFileTruncatedResponseRemovesPartialFile(t *testing.T) {
|
|||||||
}))
|
}))
|
||||||
defer ts.Close()
|
defer ts.Close()
|
||||||
|
|
||||||
d := NewWithOptions(true, false)
|
d := NewWithOptions(true, false, 0)
|
||||||
out := filepath.Join(t.TempDir(), "x", "a.bin")
|
out := filepath.Join(t.TempDir(), "x", "a.bin")
|
||||||
err := d.File(context.Background(), ts.URL, out)
|
err := d.File(context.Background(), ts.URL, out)
|
||||||
if err == nil || !errors.Is(err, io.ErrUnexpectedEOF) {
|
if err == nil || !errors.Is(err, io.ErrUnexpectedEOF) {
|
||||||
@@ -157,7 +135,7 @@ func TestFileDeezerEncryptedTruncatedResponseRemovesPartialFile(t *testing.T) {
|
|||||||
}))
|
}))
|
||||||
defer ts.Close()
|
defer ts.Close()
|
||||||
|
|
||||||
d := NewWithOptions(true, false)
|
d := NewWithOptions(true, false, 0)
|
||||||
out := filepath.Join(t.TempDir(), "x", "a.flac")
|
out := filepath.Join(t.TempDir(), "x", "a.flac")
|
||||||
err := d.FileDeezerEncrypted(context.Background(), ts.URL, out, "3135556")
|
err := d.FileDeezerEncrypted(context.Background(), ts.URL, out, "3135556")
|
||||||
if err == nil || !errors.Is(err, io.ErrUnexpectedEOF) {
|
if err == nil || !errors.Is(err, io.ErrUnexpectedEOF) {
|
||||||
@@ -174,7 +152,7 @@ func TestFileDeezerEncryptedBadStatus(t *testing.T) {
|
|||||||
}))
|
}))
|
||||||
defer ts.Close()
|
defer ts.Close()
|
||||||
|
|
||||||
d := NewWithOptions(true, false)
|
d := NewWithOptions(true, false, 0)
|
||||||
out := filepath.Join(t.TempDir(), "x", "a.flac")
|
out := filepath.Join(t.TempDir(), "x", "a.flac")
|
||||||
err := d.FileDeezerEncrypted(context.Background(), ts.URL, out, "3135556")
|
err := d.FileDeezerEncrypted(context.Background(), ts.URL, out, "3135556")
|
||||||
if err == nil || !strings.Contains(err.Error(), "status=403") {
|
if err == nil || !strings.Contains(err.Error(), "status=403") {
|
||||||
@@ -193,7 +171,7 @@ func TestDownloaderFileContextCancellationRemovesPartialFile(t *testing.T) {
|
|||||||
}))
|
}))
|
||||||
defer ts.Close()
|
defer ts.Close()
|
||||||
|
|
||||||
d := NewWithOptions(true, false)
|
d := NewWithOptions(true, false, 0)
|
||||||
out := filepath.Join(t.TempDir(), "x", "cancel.bin")
|
out := filepath.Join(t.TempDir(), "x", "cancel.bin")
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Millisecond)
|
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Millisecond)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
@@ -207,7 +185,7 @@ func TestDownloaderFileContextCancellationRemovesPartialFile(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestStreamManifestWithFFmpegMissing(t *testing.T) {
|
func TestStreamManifestWithFFmpegMissing(t *testing.T) {
|
||||||
d := NewWithOptions(true, false)
|
d := NewWithOptions(true, false, 0)
|
||||||
t.Setenv("PATH", "")
|
t.Setenv("PATH", "")
|
||||||
err := d.streamManifestWithFFmpeg(context.Background(), "https://example.com/live.m3u8", filepath.Join(t.TempDir(), "out.m4a"), false)
|
err := d.streamManifestWithFFmpeg(context.Background(), "https://example.com/live.m3u8", filepath.Join(t.TempDir(), "out.m4a"), false)
|
||||||
if err == nil || !strings.Contains(strings.ToLower(err.Error()), "ffmpeg not found") {
|
if err == nil || !strings.Contains(strings.ToLower(err.Error()), "ffmpeg not found") {
|
||||||
@@ -219,7 +197,7 @@ func TestStreamManifestWithFFmpegFailureRemovesPartialFile(t *testing.T) {
|
|||||||
if _, err := exec.LookPath("ffmpeg"); err != nil {
|
if _, err := exec.LookPath("ffmpeg"); err != nil {
|
||||||
t.Skip("ffmpeg not installed")
|
t.Skip("ffmpeg not installed")
|
||||||
}
|
}
|
||||||
d := NewWithOptions(true, false)
|
d := NewWithOptions(true, false, 0)
|
||||||
out := filepath.Join(t.TempDir(), "out.m4a")
|
out := filepath.Join(t.TempDir(), "out.m4a")
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
@@ -231,3 +209,111 @@ func TestStreamManifestWithFFmpegFailureRemovesPartialFile(t *testing.T) {
|
|||||||
t.Fatalf("expected no partial file after ffmpeg failure, stat err=%v", statErr)
|
t.Fatalf("expected no partial file after ffmpeg failure, stat err=%v", statErr)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestParseFFmpegDurationLine(t *testing.T) {
|
||||||
|
totalMS, ok := parseFFmpegDurationLine(" Duration: 00:04:52.57, start: 0.000000, bitrate: 975 kb/s")
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("expected duration parse to succeed")
|
||||||
|
}
|
||||||
|
if want := int64(292570); totalMS != want {
|
||||||
|
t.Fatalf("unexpected duration ms: got=%d want=%d", totalMS, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParseFFmpegDurationBitrateBPS(t *testing.T) {
|
||||||
|
bps, ok := parseFFmpegDurationBitrateBPS(" Duration: 00:04:52.57, start: 0.000000, bitrate: 975 kb/s")
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("expected bitrate parse to succeed")
|
||||||
|
}
|
||||||
|
if want := int64(975000); bps != want {
|
||||||
|
t.Fatalf("unexpected bitrate: got=%d want=%d", bps, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParseFFmpegProgressBitrateBPS(t *testing.T) {
|
||||||
|
bps, ok := parseFFmpegProgressBitrateBPS("bitrate=1706.8kbits/s")
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("expected progress bitrate parse to succeed")
|
||||||
|
}
|
||||||
|
if want := int64(1706800); bps != want {
|
||||||
|
t.Fatalf("unexpected bitrate: got=%d want=%d", bps, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParseFFmpegTotalSize(t *testing.T) {
|
||||||
|
size, ok := parseFFmpegTotalSize("total_size=1234567")
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("expected total_size parse to succeed")
|
||||||
|
}
|
||||||
|
if want := int64(1234567); size != want {
|
||||||
|
t.Fatalf("unexpected total_size: got=%d want=%d", size, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParseFFmpegOutTime(t *testing.T) {
|
||||||
|
currentMS, ok := parseFFmpegOutTime("out_time=00:01:02.340000")
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("expected out_time parse to succeed")
|
||||||
|
}
|
||||||
|
if want := int64(62340); currentMS != want {
|
||||||
|
t.Fatalf("unexpected out_time ms: got=%d want=%d", currentMS, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParseClockDurationMSInvalid(t *testing.T) {
|
||||||
|
if _, ok := parseClockDurationMS("bad"); ok {
|
||||||
|
t.Fatalf("expected invalid duration to fail")
|
||||||
|
}
|
||||||
|
if _, ok := parseClockDurationMS("00:12"); ok {
|
||||||
|
t.Fatalf("expected short duration to fail")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEstimateTotalBytesFromBitrate(t *testing.T) {
|
||||||
|
total := estimateTotalBytesFromBitrate(10000, 1600000)
|
||||||
|
if want := int64(2000000); total != want {
|
||||||
|
t.Fatalf("unexpected estimate from bitrate: got=%d want=%d", total, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEstimateTotalBytesFromProgress(t *testing.T) {
|
||||||
|
total := estimateTotalBytesFromProgress(10000, 2500, 500000)
|
||||||
|
if want := int64(2000000); total != want {
|
||||||
|
t.Fatalf("unexpected estimate from progress: got=%d want=%d", total, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBuildFFmpegStreamArgsAudioOnly(t *testing.T) {
|
||||||
|
args := buildFFmpegStreamArgs("https://example.com/master.m3u8", "/tmp/out.m4a", false)
|
||||||
|
if !containsArgPair(args, "-map", "0:a:0") {
|
||||||
|
t.Fatalf("expected audio map in args: %v", args)
|
||||||
|
}
|
||||||
|
if containsArgPair(args, "-map", "0:v:0?") {
|
||||||
|
t.Fatalf("did not expect video map in audio-only args: %v", args)
|
||||||
|
}
|
||||||
|
if containsArgPair(args, "-map", "0") {
|
||||||
|
t.Fatalf("did not expect broad map=0 in args: %v", args)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBuildFFmpegStreamArgsIncludeVideo(t *testing.T) {
|
||||||
|
args := buildFFmpegStreamArgs("https://example.com/master.m3u8", "/tmp/out.mp4", true)
|
||||||
|
if !containsArgPair(args, "-map", "0:v:0?") {
|
||||||
|
t.Fatalf("expected video map in args: %v", args)
|
||||||
|
}
|
||||||
|
if !containsArgPair(args, "-map", "0:a:0?") {
|
||||||
|
t.Fatalf("expected audio map in args: %v", args)
|
||||||
|
}
|
||||||
|
if containsArgPair(args, "-map", "0") {
|
||||||
|
t.Fatalf("did not expect broad map=0 in args: %v", args)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func containsArgPair(args []string, key, value string) bool {
|
||||||
|
for i := 0; i+1 < len(args); i++ {
|
||||||
|
if args[i] == key && args[i+1] == value {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|||||||
131
internal/jsonutil/jsonutil.go
Normal file
131
internal/jsonutil/jsonutil.go
Normal file
@@ -0,0 +1,131 @@
|
|||||||
|
// Package jsonutil provides shared helpers for working with untyped JSON
|
||||||
|
// values (map[string]any) that come from API responses across all providers.
|
||||||
|
package jsonutil
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// StringFromAny converts a dynamic JSON value to a string.
|
||||||
|
// Numeric types are formatted without trailing zeroes.
|
||||||
|
func StringFromAny(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 ""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// IntFromAny converts a dynamic JSON value to an int.
|
||||||
|
// Handles int, int64, float64, and string types.
|
||||||
|
func IntFromAny(v any) int {
|
||||||
|
switch t := v.(type) {
|
||||||
|
case int:
|
||||||
|
return t
|
||||||
|
case int32:
|
||||||
|
return int(t)
|
||||||
|
case int64:
|
||||||
|
return int(t)
|
||||||
|
case float64:
|
||||||
|
return int(t)
|
||||||
|
case string:
|
||||||
|
i, _ := strconv.Atoi(strings.TrimSpace(t))
|
||||||
|
return i
|
||||||
|
default:
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// FloatFromAny converts a dynamic JSON value to a float64.
|
||||||
|
func FloatFromAny(v any) float64 {
|
||||||
|
switch t := v.(type) {
|
||||||
|
case float64:
|
||||||
|
return t
|
||||||
|
case int:
|
||||||
|
return float64(t)
|
||||||
|
case int64:
|
||||||
|
return float64(t)
|
||||||
|
default:
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// BoolFromAny converts a dynamic JSON value to a bool.
|
||||||
|
// Supports bool, string ("true"/"1"/"yes"), and numeric types.
|
||||||
|
func BoolFromAny(v any) bool {
|
||||||
|
switch t := v.(type) {
|
||||||
|
case bool:
|
||||||
|
return t
|
||||||
|
case string:
|
||||||
|
l := strings.ToLower(strings.TrimSpace(t))
|
||||||
|
return l == "1" || l == "true" || l == "yes"
|
||||||
|
case int:
|
||||||
|
return t != 0
|
||||||
|
case int64:
|
||||||
|
return t != 0
|
||||||
|
case float64:
|
||||||
|
return t != 0
|
||||||
|
default:
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// FirstNonEmpty returns the first string in items that is non-empty after trimming.
|
||||||
|
func FirstNonEmpty(items ...string) string {
|
||||||
|
for _, item := range items {
|
||||||
|
if strings.TrimSpace(item) != "" {
|
||||||
|
return strings.TrimSpace(item)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// NestedMap returns the value at m[key] as a map[string]any.
|
||||||
|
// Returns an empty map if the key is missing or the value is not a map.
|
||||||
|
func NestedMap(m map[string]any, key string) map[string]any {
|
||||||
|
v, ok := m[key].(map[string]any)
|
||||||
|
if !ok {
|
||||||
|
return map[string]any{}
|
||||||
|
}
|
||||||
|
return v
|
||||||
|
}
|
||||||
|
|
||||||
|
// NestedAny traverses a chain of map keys and returns the final value.
|
||||||
|
func NestedAny(v map[string]any, keys ...string) any {
|
||||||
|
cur := any(v)
|
||||||
|
for _, key := range keys {
|
||||||
|
m, ok := cur.(map[string]any)
|
||||||
|
if !ok {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
cur = m[key]
|
||||||
|
}
|
||||||
|
return cur
|
||||||
|
}
|
||||||
|
|
||||||
|
// NestedString traverses a chain of map keys and returns the final value as a string.
|
||||||
|
func NestedString(v map[string]any, keys ...string) string {
|
||||||
|
return StringFromAny(NestedAny(v, keys...))
|
||||||
|
}
|
||||||
|
|
||||||
|
// TitleCase capitalises the first rune of s. This is a simple ASCII replacement
|
||||||
|
// for the deprecated strings.Title function, suitable for source names like
|
||||||
|
// "qobuz" → "Qobuz".
|
||||||
|
func TitleCase(s string) string {
|
||||||
|
if s == "" {
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
r := []rune(s)
|
||||||
|
if r[0] >= 'a' && r[0] <= 'z' {
|
||||||
|
r[0] -= 'a' - 'A'
|
||||||
|
}
|
||||||
|
return string(r)
|
||||||
|
}
|
||||||
@@ -6,13 +6,38 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
func NewHTTPClient(timeout time.Duration, verifySSL bool) *http.Client {
|
const defaultMaxConnsPerHost = 16
|
||||||
|
|
||||||
|
// NewHTTPClient builds an *http.Client whose transport is tuned for the
|
||||||
|
// concurrent download workloads this app issues against single CDN hosts.
|
||||||
|
//
|
||||||
|
// maxConnsPerHost caps idle keep-alive sockets per host; pass <= 0 to use a
|
||||||
|
// sensible default. The downloader and provider clients should pass the
|
||||||
|
// configured concurrency so keep-alive sockets aren't evicted between workers.
|
||||||
|
func NewHTTPClient(timeout time.Duration, verifySSL bool, maxConnsPerHost int) *http.Client {
|
||||||
|
if maxConnsPerHost <= 0 {
|
||||||
|
maxConnsPerHost = defaultMaxConnsPerHost
|
||||||
|
}
|
||||||
|
|
||||||
transport := http.DefaultTransport.(*http.Transport).Clone()
|
transport := http.DefaultTransport.(*http.Transport).Clone()
|
||||||
if transport.TLSClientConfig == nil {
|
if transport.TLSClientConfig == nil {
|
||||||
transport.TLSClientConfig = &tls.Config{}
|
transport.TLSClientConfig = &tls.Config{}
|
||||||
}
|
}
|
||||||
transport.TLSClientConfig.InsecureSkipVerify = !verifySSL
|
transport.TLSClientConfig.InsecureSkipVerify = !verifySSL
|
||||||
|
|
||||||
|
transport.MaxIdleConnsPerHost = maxConnsPerHost
|
||||||
|
if maxIdle := maxConnsPerHost * 4; maxIdle > transport.MaxIdleConns {
|
||||||
|
transport.MaxIdleConns = maxIdle
|
||||||
|
}
|
||||||
|
if transport.MaxIdleConns < 100 {
|
||||||
|
transport.MaxIdleConns = 100
|
||||||
|
}
|
||||||
|
transport.MaxConnsPerHost = 0
|
||||||
|
transport.IdleConnTimeout = 90 * time.Second
|
||||||
|
transport.WriteBufferSize = 64 * 1024
|
||||||
|
transport.ReadBufferSize = 64 * 1024
|
||||||
|
transport.ForceAttemptHTTP2 = true
|
||||||
|
|
||||||
return &http.Client{
|
return &http.Client{
|
||||||
Timeout: timeout,
|
Timeout: timeout,
|
||||||
Transport: transport,
|
Transport: transport,
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -9,6 +9,8 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"streamrip-go/internal/jsonutil"
|
||||||
|
|
||||||
"streamrip-go/internal/config"
|
"streamrip-go/internal/config"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -89,7 +91,7 @@ func TestGetMetadataArtistPaginatesAlbums(t *testing.T) {
|
|||||||
if len(items) != 101 {
|
if len(items) != 101 {
|
||||||
t.Fatalf("albums len = %d, want 101", len(items))
|
t.Fatalf("albums len = %d, want 101", len(items))
|
||||||
}
|
}
|
||||||
if got := strings.TrimSpace(stringFromAny(meta["name"])); got != "Lost Frequencies" {
|
if got := strings.TrimSpace(jsonutil.StringFromAny(meta["name"])); got != "Lost Frequencies" {
|
||||||
t.Fatalf("artist name = %q, want Lost Frequencies", got)
|
t.Fatalf("artist name = %q, want Lost Frequencies", got)
|
||||||
}
|
}
|
||||||
if callCount != 2 {
|
if callCount != 2 {
|
||||||
@@ -97,12 +99,141 @@ func TestGetMetadataArtistPaginatesAlbums(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestGetMetadataAlbumPaginatesTracks(t *testing.T) {
|
||||||
|
callCount := 0
|
||||||
|
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
switch r.URL.Path {
|
||||||
|
case "/album/46514392":
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]any{"id": 46514392, "title": "Clouseau30", "tracks": map[string]any{"data": []any{}}})
|
||||||
|
case "/album/46514392/tracks":
|
||||||
|
callCount++
|
||||||
|
index := r.URL.Query().Get("index")
|
||||||
|
limit := r.URL.Query().Get("limit")
|
||||||
|
if limit != "100" {
|
||||||
|
w.WriteHeader(http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
switch index {
|
||||||
|
case "0":
|
||||||
|
items := make([]any, 0, 100)
|
||||||
|
for i := 0; i < 100; i++ {
|
||||||
|
items = append(items, map[string]any{"id": i + 1, "title": "T"})
|
||||||
|
}
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]any{"data": items, "total": 105})
|
||||||
|
case "100":
|
||||||
|
items := make([]any, 0, 5)
|
||||||
|
for i := 0; i < 5; i++ {
|
||||||
|
items = append(items, map[string]any{"id": 101 + i, "title": "T"})
|
||||||
|
}
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]any{"data": items, "total": 105})
|
||||||
|
default:
|
||||||
|
w.WriteHeader(http.StatusBadRequest)
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
w.WriteHeader(http.StatusNotFound)
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
defer ts.Close()
|
||||||
|
|
||||||
|
cfgData := config.DefaultConfigData()
|
||||||
|
c := New(&config.Config{File: cfgData, Session: cfgData})
|
||||||
|
c.loggedIn = true
|
||||||
|
|
||||||
|
origBase := baseURL
|
||||||
|
baseURL = ts.URL
|
||||||
|
defer func() { baseURL = origBase }()
|
||||||
|
|
||||||
|
meta, err := c.GetMetadata(context.Background(), "46514392", "album")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("GetMetadata() error = %v", err)
|
||||||
|
}
|
||||||
|
tracksObj, _ := meta["tracks"].(map[string]any)
|
||||||
|
items, _ := tracksObj["items"].([]any)
|
||||||
|
if len(items) != 105 {
|
||||||
|
t.Fatalf("tracks len = %d, want 105", len(items))
|
||||||
|
}
|
||||||
|
if callCount != 2 {
|
||||||
|
t.Fatalf("track page call count = %d, want 2", callCount)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGetMetadataPlaylistPaginatesTracks(t *testing.T) {
|
||||||
|
callCount := 0
|
||||||
|
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
switch r.URL.Path {
|
||||||
|
case "/playlist/123":
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]any{"id": 123, "title": "Mix", "tracks": map[string]any{"data": []any{}}})
|
||||||
|
case "/playlist/123/tracks":
|
||||||
|
callCount++
|
||||||
|
index := r.URL.Query().Get("index")
|
||||||
|
limit := r.URL.Query().Get("limit")
|
||||||
|
if limit != "100" {
|
||||||
|
w.WriteHeader(http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
switch index {
|
||||||
|
case "0":
|
||||||
|
items := make([]any, 0, 100)
|
||||||
|
for i := 0; i < 100; i++ {
|
||||||
|
items = append(items, map[string]any{"id": i + 1, "title": "T"})
|
||||||
|
}
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]any{"data": items, "total": 101})
|
||||||
|
case "100":
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]any{"data": []any{map[string]any{"id": 101, "title": "T"}}, "total": 101})
|
||||||
|
default:
|
||||||
|
w.WriteHeader(http.StatusBadRequest)
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
w.WriteHeader(http.StatusNotFound)
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
defer ts.Close()
|
||||||
|
|
||||||
|
cfgData := config.DefaultConfigData()
|
||||||
|
c := New(&config.Config{File: cfgData, Session: cfgData})
|
||||||
|
c.loggedIn = true
|
||||||
|
|
||||||
|
origBase := baseURL
|
||||||
|
baseURL = ts.URL
|
||||||
|
defer func() { baseURL = origBase }()
|
||||||
|
|
||||||
|
meta, err := c.GetMetadata(context.Background(), "123", "playlist")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("GetMetadata() error = %v", err)
|
||||||
|
}
|
||||||
|
tracksObj, _ := meta["tracks"].(map[string]any)
|
||||||
|
items, _ := tracksObj["items"].([]any)
|
||||||
|
if len(items) != 101 {
|
||||||
|
t.Fatalf("tracks len = %d, want 101", len(items))
|
||||||
|
}
|
||||||
|
if callCount != 2 {
|
||||||
|
t.Fatalf("track page call count = %d, want 2", callCount)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestGetDownloadableNativeCipher(t *testing.T) {
|
func TestGetDownloadableNativeCipher(t *testing.T) {
|
||||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
switch r.URL.Path {
|
switch r.URL.Path {
|
||||||
case "/track/42":
|
case "/track/42":
|
||||||
_ = json.NewEncoder(w).Encode(map[string]any{"id": 42, "title": "X", "track_token": "tt"})
|
_ = json.NewEncoder(w).Encode(map[string]any{"id": 42, "title": "X", "track_token": "tt"})
|
||||||
case "/media":
|
case "/media":
|
||||||
|
if got := strings.TrimSpace(r.Header.Get("Accept-Charset")); got != "UTF-8" {
|
||||||
|
t.Fatalf("accept-charset = %q, want UTF-8", got)
|
||||||
|
}
|
||||||
|
var payload map[string]any
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
|
||||||
|
w.WriteHeader(http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
media, _ := payload["media"].([]any)
|
||||||
|
if len(media) != 1 {
|
||||||
|
t.Fatalf("media length = %d, want 1", len(media))
|
||||||
|
}
|
||||||
|
entry, _ := media[0].(map[string]any)
|
||||||
|
formats, _ := entry["formats"].([]any)
|
||||||
|
if len(formats) != 6 {
|
||||||
|
t.Fatalf("formats length = %d, want 6", len(formats))
|
||||||
|
}
|
||||||
_ = json.NewEncoder(w).Encode(map[string]any{"data": []any{map[string]any{"errors": []any{}, "media": []any{map[string]any{"cipher": map[string]any{"type": "BF_CBC_STRIPE"}, "format": "FLAC", "sources": []any{map[string]any{"url": "https://cdn.example/file"}}}}}}})
|
_ = json.NewEncoder(w).Encode(map[string]any{"data": []any{map[string]any{"errors": []any{}, "media": []any{map[string]any{"cipher": map[string]any{"type": "BF_CBC_STRIPE"}, "format": "FLAC", "sources": []any{map[string]any{"url": "https://cdn.example/file"}}}}}}})
|
||||||
default:
|
default:
|
||||||
w.WriteHeader(http.StatusNotFound)
|
w.WriteHeader(http.StatusNotFound)
|
||||||
@@ -137,6 +268,121 @@ func TestGetDownloadableNativeCipher(t *testing.T) {
|
|||||||
if d.Cipher != "BF_CBC_STRIPE" || d.Extension != "flac" || d.TrackID != "42" {
|
if d.Cipher != "BF_CBC_STRIPE" || d.Extension != "flac" || d.TrackID != "42" {
|
||||||
t.Fatalf("unexpected downloadable: %+v", d)
|
t.Fatalf("unexpected downloadable: %+v", d)
|
||||||
}
|
}
|
||||||
|
if d.Audio.Container != "FLAC" || d.Audio.Quality != "LOSSLESS" {
|
||||||
|
t.Fatalf("unexpected audio profile: %+v", d.Audio)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGetDownloadablePrefersNoneCipherWhenAvailable(t *testing.T) {
|
||||||
|
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
switch r.URL.Path {
|
||||||
|
case "/track/42":
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]any{"id": 42, "title": "X", "track_token": "tt"})
|
||||||
|
case "/media":
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]any{"data": []any{map[string]any{"errors": []any{}, "media": []any{
|
||||||
|
map[string]any{"cipher": map[string]any{"type": "BF_CBC_STRIPE"}, "format": "FLAC", "sources": []any{map[string]any{"url": "https://cdn.example/bf"}}},
|
||||||
|
map[string]any{"cipher": map[string]any{"type": "NONE"}, "format": "FLAC", "sources": []any{map[string]any{"url": "https://cdn.example/plain"}}},
|
||||||
|
}}}})
|
||||||
|
default:
|
||||||
|
w.WriteHeader(http.StatusNotFound)
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
defer ts.Close()
|
||||||
|
|
||||||
|
cfgData := config.DefaultConfigData()
|
||||||
|
cfgData.Deezer.ARL = "arl"
|
||||||
|
c := New(&config.Config{File: cfgData, Session: cfgData})
|
||||||
|
c.loggedIn = true
|
||||||
|
c.arl = "arl"
|
||||||
|
c.license = "license"
|
||||||
|
c.jwt = "jwt"
|
||||||
|
|
||||||
|
origBase := baseURL
|
||||||
|
origMedia := mediaURL
|
||||||
|
origPipe := pipeURL
|
||||||
|
baseURL = ts.URL
|
||||||
|
mediaURL = ts.URL + "/media"
|
||||||
|
pipeURL = ts.URL + "/pipe"
|
||||||
|
defer func() {
|
||||||
|
baseURL = origBase
|
||||||
|
mediaURL = origMedia
|
||||||
|
pipeURL = origPipe
|
||||||
|
}()
|
||||||
|
|
||||||
|
d, err := c.GetDownloadable(context.Background(), "42", 2)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("GetDownloadable() error = %v", err)
|
||||||
|
}
|
||||||
|
if d.Cipher != "NONE" || d.URL != "https://cdn.example/plain" {
|
||||||
|
t.Fatalf("expected NONE cipher source, got %+v", d)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestExtractTrackIDFromMediaURL(t *testing.T) {
|
||||||
|
url := "https://f-cdnt-stream.dzcdn.net/media/1/9/6/4/8/2552667002/64821d6a2007e90768fa0300b508fcf4.flac?hdnea=x"
|
||||||
|
if got := extractTrackIDFromMediaURL(url); got != "2552667002" {
|
||||||
|
t.Fatalf("extractTrackIDFromMediaURL() = %q, want 2552667002", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoginPrefersARLFlowOverRefreshShortcut(t *testing.T) {
|
||||||
|
mobileToken := testMobileToken(t)
|
||||||
|
refreshCalled := false
|
||||||
|
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
switch r.URL.Path {
|
||||||
|
case "/web":
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]any{"results": map[string]any{"USER_ID": "42", "JWT": "jwt-from-web", "refresh_token": "refresh-from-web", "license_token": "license-from-web"}})
|
||||||
|
case "/gateway":
|
||||||
|
switch r.URL.Query().Get("method") {
|
||||||
|
case "mobile_auth":
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]any{"results": map[string]any{"TOKEN": mobileToken}})
|
||||||
|
case "api_checkToken":
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]any{"results": "sid123"})
|
||||||
|
case "mobile_userAutolog":
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]any{"results": map[string]any{"JWT": "jwt-from-autolog", "license_token": "license-from-autolog", "refresh_token": "refresh-from-autolog"}})
|
||||||
|
default:
|
||||||
|
w.WriteHeader(http.StatusNotFound)
|
||||||
|
}
|
||||||
|
case "/pipe":
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]any{"data": map[string]any{"tokens": map[string]any{"mediaServiceLicenseToken": map[string]any{"token": "license-from-pipe"}}}})
|
||||||
|
case "/renew":
|
||||||
|
refreshCalled = true
|
||||||
|
w.WriteHeader(http.StatusInternalServerError)
|
||||||
|
default:
|
||||||
|
w.WriteHeader(http.StatusNotFound)
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
defer ts.Close()
|
||||||
|
|
||||||
|
cfgData := config.DefaultConfigData()
|
||||||
|
cfgData.Deezer.ARL = "arl"
|
||||||
|
cfgData.Deezer.RefreshToken = "refresh-token"
|
||||||
|
c := New(&config.Config{File: cfgData, Session: cfgData})
|
||||||
|
|
||||||
|
origGateway := gatewayURL
|
||||||
|
origWeb := webGWLight
|
||||||
|
origPipe := pipeURL
|
||||||
|
origAuth := authURL
|
||||||
|
gatewayURL = ts.URL + "/gateway"
|
||||||
|
webGWLight = ts.URL + "/web"
|
||||||
|
pipeURL = ts.URL + "/pipe"
|
||||||
|
authURL = ts.URL + "/renew"
|
||||||
|
defer func() {
|
||||||
|
gatewayURL = origGateway
|
||||||
|
webGWLight = origWeb
|
||||||
|
pipeURL = origPipe
|
||||||
|
authURL = origAuth
|
||||||
|
}()
|
||||||
|
|
||||||
|
if err := c.Login(context.Background()); err != nil {
|
||||||
|
t.Fatalf("Login() error = %v", err)
|
||||||
|
}
|
||||||
|
if refreshCalled {
|
||||||
|
t.Fatalf("expected ARL launch flow without refresh shortcut")
|
||||||
|
}
|
||||||
|
if c.license != "license-from-pipe" {
|
||||||
|
t.Fatalf("license = %q, want license-from-pipe", c.license)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestGetDownloadableRequiresARL(t *testing.T) {
|
func TestGetDownloadableRequiresARL(t *testing.T) {
|
||||||
@@ -189,6 +435,99 @@ func TestGetDownloadableDRMError(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestGetTrackTokenPrefersPipeToken(t *testing.T) {
|
||||||
|
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
switch r.URL.Path {
|
||||||
|
case "/pipe":
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]any{"data": map[string]any{"track": map[string]any{"media": map[string]any{"token": map[string]any{"payload": "pipe-track-token"}}}}})
|
||||||
|
case "/track/42":
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]any{"id": 42, "track_token": "api-track-token"})
|
||||||
|
default:
|
||||||
|
w.WriteHeader(http.StatusNotFound)
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
defer ts.Close()
|
||||||
|
|
||||||
|
cfgData := config.DefaultConfigData()
|
||||||
|
c := New(&config.Config{File: cfgData, Session: cfgData})
|
||||||
|
c.loggedIn = true
|
||||||
|
c.jwt = "jwt-token"
|
||||||
|
|
||||||
|
origBase := baseURL
|
||||||
|
origPipe := pipeURL
|
||||||
|
baseURL = ts.URL
|
||||||
|
pipeURL = ts.URL + "/pipe"
|
||||||
|
defer func() {
|
||||||
|
baseURL = origBase
|
||||||
|
pipeURL = origPipe
|
||||||
|
}()
|
||||||
|
|
||||||
|
token, mediaID, err := c.getTrackToken(context.Background(), "42")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("getTrackToken() error = %v", err)
|
||||||
|
}
|
||||||
|
if token != "pipe-track-token" {
|
||||||
|
t.Fatalf("token = %q, want pipe-track-token", token)
|
||||||
|
}
|
||||||
|
if mediaID != "" {
|
||||||
|
t.Fatalf("mediaID = %q, want empty when pipe media id missing", mediaID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGetDownloadableUsesPipeTrackToken(t *testing.T) {
|
||||||
|
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
switch r.URL.Path {
|
||||||
|
case "/track/42":
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]any{"id": 42, "title": "X", "track_token": "api-track-token"})
|
||||||
|
case "/pipe":
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]any{"data": map[string]any{"track": map[string]any{"media": map[string]any{"token": map[string]any{"payload": "pipe-track-token"}}}}})
|
||||||
|
case "/media":
|
||||||
|
var payload map[string]any
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
|
||||||
|
w.WriteHeader(http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
tokens, _ := payload["track_tokens"].([]any)
|
||||||
|
if len(tokens) == 0 || strings.TrimSpace(jsonutil.StringFromAny(tokens[0])) != "pipe-track-token" {
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]any{"data": []any{map[string]any{"errors": []any{map[string]any{"code": 2004, "message": "The track country differs from the license."}}, "media": []any{}}}})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]any{"data": []any{map[string]any{"errors": []any{}, "media": []any{map[string]any{"cipher": map[string]any{"type": "BF_CBC_STRIPE"}, "format": "FLAC", "sources": []any{map[string]any{"url": "https://cdn.example/file"}}}}}}})
|
||||||
|
default:
|
||||||
|
w.WriteHeader(http.StatusNotFound)
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
defer ts.Close()
|
||||||
|
|
||||||
|
cfgData := config.DefaultConfigData()
|
||||||
|
cfgData.Deezer.ARL = "arl"
|
||||||
|
c := New(&config.Config{File: cfgData, Session: cfgData})
|
||||||
|
c.loggedIn = true
|
||||||
|
c.arl = "arl"
|
||||||
|
c.license = "license"
|
||||||
|
c.jwt = "jwt"
|
||||||
|
|
||||||
|
origBase := baseURL
|
||||||
|
origMedia := mediaURL
|
||||||
|
origPipe := pipeURL
|
||||||
|
baseURL = ts.URL
|
||||||
|
mediaURL = ts.URL + "/media"
|
||||||
|
pipeURL = ts.URL + "/pipe"
|
||||||
|
defer func() {
|
||||||
|
baseURL = origBase
|
||||||
|
mediaURL = origMedia
|
||||||
|
pipeURL = origPipe
|
||||||
|
}()
|
||||||
|
|
||||||
|
d, err := c.GetDownloadable(context.Background(), "42", 2)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("GetDownloadable() error = %v", err)
|
||||||
|
}
|
||||||
|
if d.URL != "https://cdn.example/file" || d.Extension != "flac" {
|
||||||
|
t.Fatalf("unexpected downloadable: %+v", d)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestGetMetadataAddsLyricsFromPipe(t *testing.T) {
|
func TestGetMetadataAddsLyricsFromPipe(t *testing.T) {
|
||||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
switch r.URL.Path {
|
switch r.URL.Path {
|
||||||
@@ -220,11 +559,11 @@ func TestGetMetadataAddsLyricsFromPipe(t *testing.T) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("GetMetadata() error = %v", err)
|
t.Fatalf("GetMetadata() error = %v", err)
|
||||||
}
|
}
|
||||||
if !strings.Contains(stringFromAny(meta["lyrics"]), "Go shawty") {
|
if !strings.Contains(jsonutil.StringFromAny(meta["lyrics"]), "Go shawty") {
|
||||||
t.Fatalf("expected lyrics text, got %q", stringFromAny(meta["lyrics"]))
|
t.Fatalf("expected lyrics text, got %q", jsonutil.StringFromAny(meta["lyrics"]))
|
||||||
}
|
}
|
||||||
if !strings.Contains(stringFromAny(meta["lyrics_synced"]), "[00:00.00]Go, go, go") {
|
if !strings.Contains(jsonutil.StringFromAny(meta["lyrics_synced"]), "[00:00.00]Go, go, go") {
|
||||||
t.Fatalf("expected synced lyrics, got %q", stringFromAny(meta["lyrics_synced"]))
|
t.Fatalf("expected synced lyrics, got %q", jsonutil.StringFromAny(meta["lyrics_synced"]))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -243,7 +582,7 @@ func TestLoginWithCredentials(t *testing.T) {
|
|||||||
case "mobile_userAuth":
|
case "mobile_userAuth":
|
||||||
var payload map[string]any
|
var payload map[string]any
|
||||||
_ = json.NewDecoder(r.Body).Decode(&payload)
|
_ = json.NewDecoder(r.Body).Decode(&payload)
|
||||||
if strings.TrimSpace(stringFromAny(payload["mail"])) == "" || strings.TrimSpace(stringFromAny(payload["password"])) == "" {
|
if strings.TrimSpace(jsonutil.StringFromAny(payload["mail"])) == "" || strings.TrimSpace(jsonutil.StringFromAny(payload["password"])) == "" {
|
||||||
w.WriteHeader(http.StatusBadRequest)
|
w.WriteHeader(http.StatusBadRequest)
|
||||||
_ = json.NewEncoder(w).Encode(map[string]any{"error": map[string]any{"message": "missing creds"}})
|
_ = json.NewEncoder(w).Encode(map[string]any{"error": map[string]any{"message": "missing creds"}})
|
||||||
return
|
return
|
||||||
@@ -290,6 +629,102 @@ func TestLoginWithCredentials(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestMobileAuthIncludesAppContextParams(t *testing.T) {
|
||||||
|
mobileToken := testMobileToken(t)
|
||||||
|
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.URL.Path != "/gateway" {
|
||||||
|
w.WriteHeader(http.StatusNotFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if r.URL.Query().Get("method") != "mobile_auth" {
|
||||||
|
w.WriteHeader(http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if got := strings.TrimSpace(r.URL.Query().Get("version")); got != deezerAppVersion {
|
||||||
|
t.Fatalf("version = %q, want %q", got, deezerAppVersion)
|
||||||
|
}
|
||||||
|
if got := strings.TrimSpace(r.URL.Query().Get("lang")); got != deezerAppLang {
|
||||||
|
t.Fatalf("lang = %q, want %q", got, deezerAppLang)
|
||||||
|
}
|
||||||
|
if got := strings.TrimSpace(r.URL.Query().Get("buildId")); got != deezerBuildID {
|
||||||
|
t.Fatalf("buildId = %q, want %q", got, deezerBuildID)
|
||||||
|
}
|
||||||
|
if got := strings.TrimSpace(r.URL.Query().Get("screenWidth")); got != deezerScreenW {
|
||||||
|
t.Fatalf("screenWidth = %q, want %q", got, deezerScreenW)
|
||||||
|
}
|
||||||
|
if got := strings.TrimSpace(r.URL.Query().Get("screenHeight")); got != deezerScreenH {
|
||||||
|
t.Fatalf("screenHeight = %q, want %q", got, deezerScreenH)
|
||||||
|
}
|
||||||
|
if got := strings.TrimSpace(r.URL.Query().Get("uniq_id")); got == "" {
|
||||||
|
t.Fatalf("uniq_id is empty")
|
||||||
|
}
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]any{"results": map[string]any{"TOKEN": mobileToken}})
|
||||||
|
}))
|
||||||
|
defer ts.Close()
|
||||||
|
|
||||||
|
cfgData := config.DefaultConfigData()
|
||||||
|
c := New(&config.Config{File: cfgData, Session: cfgData})
|
||||||
|
|
||||||
|
origGateway := gatewayURL
|
||||||
|
gatewayURL = ts.URL + "/gateway"
|
||||||
|
defer func() { gatewayURL = origGateway }()
|
||||||
|
|
||||||
|
token, err := c.mobileAuth(context.Background())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("mobileAuth() error = %v", err)
|
||||||
|
}
|
||||||
|
if token != mobileToken {
|
||||||
|
t.Fatalf("token = %q, want %q", token, mobileToken)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMobileUserAutologIncludesRefreshToken(t *testing.T) {
|
||||||
|
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.URL.Path != "/gateway" {
|
||||||
|
w.WriteHeader(http.StatusNotFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if method := r.URL.Query().Get("method"); method != "mobile_userAutolog" {
|
||||||
|
w.WriteHeader(http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if got := strings.TrimSpace(r.URL.Query().Get("arl")); got != "" {
|
||||||
|
t.Fatalf("unexpected arl query parameter: %q", got)
|
||||||
|
}
|
||||||
|
var payload map[string]any
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
|
||||||
|
w.WriteHeader(http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if got := strings.TrimSpace(jsonutil.StringFromAny(payload["refresh_token"])); got != "refresh-token" {
|
||||||
|
t.Fatalf("refresh_token payload = %q, want refresh-token", got)
|
||||||
|
}
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]any{"results": map[string]any{"JWT": "jwt-token", "license_token": "license-token"}})
|
||||||
|
}))
|
||||||
|
defer ts.Close()
|
||||||
|
|
||||||
|
cfgData := config.DefaultConfigData()
|
||||||
|
c := New(&config.Config{File: cfgData, Session: cfgData})
|
||||||
|
c.sid = "sid123"
|
||||||
|
c.userID = "42"
|
||||||
|
c.arl = "arl-token"
|
||||||
|
c.refresh = "refresh-token"
|
||||||
|
|
||||||
|
origGateway := gatewayURL
|
||||||
|
gatewayURL = ts.URL + "/gateway"
|
||||||
|
defer func() { gatewayURL = origGateway }()
|
||||||
|
|
||||||
|
if err := c.mobileUserAutolog(context.Background()); err != nil {
|
||||||
|
t.Fatalf("mobileUserAutolog() error = %v", err)
|
||||||
|
}
|
||||||
|
if c.jwt != "jwt-token" {
|
||||||
|
t.Fatalf("jwt = %q, want jwt-token", c.jwt)
|
||||||
|
}
|
||||||
|
if c.license != "license-token" {
|
||||||
|
t.Fatalf("license = %q, want license-token", c.license)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func testMobileToken(t *testing.T) string {
|
func testMobileToken(t *testing.T) string {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
plain := []byte(strings.Repeat("A", 64) + strings.Repeat("B", 16) + strings.Repeat("C", 16))
|
plain := []byte(strings.Repeat("A", 64) + strings.Repeat("B", 16) + strings.Repeat("C", 16))
|
||||||
@@ -380,3 +815,51 @@ func TestRefreshLicenseFromPipeGraphQLError(t *testing.T) {
|
|||||||
t.Fatalf("expected graphql error, got %v", err)
|
t.Fatalf("expected graphql error, got %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestRefreshLicenseFromPipeUsesMobileGraphQLShape(t *testing.T) {
|
||||||
|
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if got := strings.TrimSpace(r.Header.Get("Authorization")); got != "Bearer jwt-token" {
|
||||||
|
t.Fatalf("authorization = %q, want Bearer jwt-token", got)
|
||||||
|
}
|
||||||
|
if got := r.Header.Get("Accept"); !strings.Contains(got, "application/graphql-response+json") {
|
||||||
|
t.Fatalf("accept header = %q", got)
|
||||||
|
}
|
||||||
|
if got := strings.TrimSpace(r.Header.Get("Accept-Language")); got != "en-US" {
|
||||||
|
t.Fatalf("accept-language = %q, want en-US", got)
|
||||||
|
}
|
||||||
|
var payload map[string]any
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
|
||||||
|
w.WriteHeader(http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
op := strings.TrimSpace(jsonutil.StringFromAny(payload["operationName"]))
|
||||||
|
if op != "KmpMpMediaServiceLicenseToken" {
|
||||||
|
t.Fatalf("operationName = %q, want KmpMpMediaServiceLicenseToken", op)
|
||||||
|
}
|
||||||
|
ext, _ := payload["extensions"].(map[string]any)
|
||||||
|
clientLib, _ := ext["clientLibrary"].(map[string]any)
|
||||||
|
if got := strings.TrimSpace(jsonutil.StringFromAny(clientLib["name"])); got != "apollo-kotlin" {
|
||||||
|
t.Fatalf("clientLibrary.name = %q, want apollo-kotlin", got)
|
||||||
|
}
|
||||||
|
if got := strings.TrimSpace(jsonutil.StringFromAny(clientLib["version"])); got != "4.4.2" {
|
||||||
|
t.Fatalf("clientLibrary.version = %q, want 4.4.2", got)
|
||||||
|
}
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]any{"data": map[string]any{"tokens": map[string]any{"mediaServiceLicenseToken": map[string]any{"token": "license-token"}}}})
|
||||||
|
}))
|
||||||
|
defer ts.Close()
|
||||||
|
|
||||||
|
cfgData := config.DefaultConfigData()
|
||||||
|
c := New(&config.Config{File: cfgData, Session: cfgData})
|
||||||
|
c.jwt = "jwt-token"
|
||||||
|
|
||||||
|
origPipe := pipeURL
|
||||||
|
pipeURL = ts.URL
|
||||||
|
defer func() { pipeURL = origPipe }()
|
||||||
|
|
||||||
|
if err := c.refreshLicenseFromPipe(context.Background()); err != nil {
|
||||||
|
t.Fatalf("refreshLicenseFromPipe() error = %v", err)
|
||||||
|
}
|
||||||
|
if c.license != "license-token" {
|
||||||
|
t.Fatalf("license = %q, want license-token", c.license)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -8,6 +8,16 @@ type Downloadable struct {
|
|||||||
Source string
|
Source string
|
||||||
Cipher string
|
Cipher string
|
||||||
TrackID string
|
TrackID string
|
||||||
|
Audio AudioProfile
|
||||||
|
}
|
||||||
|
|
||||||
|
type AudioProfile struct {
|
||||||
|
Container string
|
||||||
|
Codec string
|
||||||
|
Quality string
|
||||||
|
BitDepth int
|
||||||
|
SamplingRate string
|
||||||
|
BitrateKbps int
|
||||||
}
|
}
|
||||||
|
|
||||||
type Client interface {
|
type Client interface {
|
||||||
|
|||||||
@@ -1,30 +1,57 @@
|
|||||||
package qobuz
|
package qobuz
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
"context"
|
"context"
|
||||||
|
"crypto/aes"
|
||||||
|
"crypto/cipher"
|
||||||
"crypto/md5"
|
"crypto/md5"
|
||||||
|
"crypto/sha256"
|
||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
"encoding/hex"
|
"encoding/hex"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"hash"
|
||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
"net/url"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
"regexp"
|
"regexp"
|
||||||
"sort"
|
"sort"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"streamrip-go/internal/config"
|
"streamrip-go/internal/config"
|
||||||
|
"streamrip-go/internal/jsonutil"
|
||||||
"streamrip-go/internal/netutil"
|
"streamrip-go/internal/netutil"
|
||||||
"streamrip-go/internal/provider"
|
"streamrip-go/internal/provider"
|
||||||
"streamrip-go/internal/ratelimit"
|
"streamrip-go/internal/ratelimit"
|
||||||
|
|
||||||
|
"github.com/vbauerster/mpb/v8"
|
||||||
|
"github.com/vbauerster/mpb/v8/decor"
|
||||||
|
"golang.org/x/crypto/hkdf"
|
||||||
)
|
)
|
||||||
|
|
||||||
const baseURL = "https://www.qobuz.com/api.json/0.2"
|
const baseURL = "https://www.qobuz.com/api.json/0.2"
|
||||||
|
|
||||||
|
const (
|
||||||
|
mobileAppID = "312369995"
|
||||||
|
mobileAppSecret = "e79f8b9be485692b0e5f9dd895826368"
|
||||||
|
mobileUserAgent = "Dalvik/2.1.0 (Linux; U; Android 9; Nexus 6P Build/PQ3A.190801.002) QobuzMobileAndroid/9.7.0.3-b26022717"
|
||||||
|
mobileAppVersion = "9.7.0.3"
|
||||||
|
mobileSessionProf = "qbz-1"
|
||||||
|
mobileSegmentTries = 3
|
||||||
|
)
|
||||||
|
|
||||||
|
var qobuzUUIDBytes = []byte{
|
||||||
|
0x3b, 0x42, 0x12, 0x92, 0x56, 0xf3, 0x5f, 0x75,
|
||||||
|
0x92, 0x36, 0x63, 0xb6, 0x9a, 0x1f, 0x52, 0xb2,
|
||||||
|
}
|
||||||
|
|
||||||
var (
|
var (
|
||||||
errMissingCredentials = errors.New("missing qobuz credentials")
|
errMissingCredentials = errors.New("missing qobuz credentials")
|
||||||
errNotLoggedIn = errors.New("qobuz client not logged in")
|
errNotLoggedIn = errors.New("qobuz client not logged in")
|
||||||
@@ -39,12 +66,29 @@ type Client struct {
|
|||||||
loggedIn bool
|
loggedIn bool
|
||||||
secret string
|
secret string
|
||||||
uat string
|
uat string
|
||||||
|
|
||||||
|
mobileMu sync.Mutex
|
||||||
|
mobileAccessToken string
|
||||||
|
mobileSessionID string
|
||||||
|
mobileSessionInfo string
|
||||||
|
mobileKEK []byte
|
||||||
|
}
|
||||||
|
|
||||||
|
type mobileFileURL struct {
|
||||||
|
URL string `json:"url"`
|
||||||
|
URLTemplate string `json:"url_template"`
|
||||||
|
NSegments int `json:"n_segments"`
|
||||||
|
FormatID int `json:"format_id"`
|
||||||
|
MimeType string `json:"mime_type"`
|
||||||
|
Sampling float64 `json:"sampling_rate"`
|
||||||
|
BitDepth int `json:"bits_depth"`
|
||||||
|
Key string `json:"key"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func New(cfg *config.Config) *Client {
|
func New(cfg *config.Config) *Client {
|
||||||
return &Client{
|
return &Client{
|
||||||
cfg: cfg,
|
cfg: cfg,
|
||||||
http: netutil.NewHTTPClient(30*time.Second, cfg.Session.Downloads.VerifySSL),
|
http: netutil.NewHTTPClient(30*time.Second, cfg.Session.Downloads.VerifySSL, cfg.Session.Downloads.MaxConnections),
|
||||||
limiter: ratelimit.New(cfg.Session.Downloads.RequestsPerMinute),
|
limiter: ratelimit.New(cfg.Session.Downloads.RequestsPerMinute),
|
||||||
baseURL: baseURL,
|
baseURL: baseURL,
|
||||||
fetchCfg: nil,
|
fetchCfg: nil,
|
||||||
@@ -274,11 +318,13 @@ func (c *Client) GetDownloadable(ctx context.Context, item string, quality int)
|
|||||||
}
|
}
|
||||||
|
|
||||||
ext := qobuzDownloadExtension(resp, quality, streamURL)
|
ext := qobuzDownloadExtension(resp, quality, streamURL)
|
||||||
|
profile := qobuzAudioProfile(resp, quality, ext)
|
||||||
|
|
||||||
return &provider.Downloadable{
|
return &provider.Downloadable{
|
||||||
URL: streamURL,
|
URL: streamURL,
|
||||||
Extension: ext,
|
Extension: ext,
|
||||||
Source: "qobuz",
|
Source: "qobuz",
|
||||||
|
Audio: profile,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -317,10 +363,201 @@ func qobuzDownloadExtension(resp map[string]any, quality int, streamURL string)
|
|||||||
return "mp3"
|
return "mp3"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func qobuzAudioProfile(resp map[string]any, requestedQuality int, ext string) provider.AudioProfile {
|
||||||
|
if formatID, ok := intValue(resp["format_id"]); ok {
|
||||||
|
switch formatID {
|
||||||
|
case 5:
|
||||||
|
return provider.AudioProfile{
|
||||||
|
Container: "MP3",
|
||||||
|
Codec: "MP3",
|
||||||
|
Quality: "HIGH",
|
||||||
|
BitDepth: 16,
|
||||||
|
SamplingRate: "44.1",
|
||||||
|
BitrateKbps: 320,
|
||||||
|
}
|
||||||
|
case 6:
|
||||||
|
return provider.AudioProfile{
|
||||||
|
Container: "FLAC",
|
||||||
|
Codec: "FLAC",
|
||||||
|
Quality: "LOSSLESS",
|
||||||
|
BitDepth: 16,
|
||||||
|
SamplingRate: "44.1",
|
||||||
|
}
|
||||||
|
case 7:
|
||||||
|
return provider.AudioProfile{
|
||||||
|
Container: "FLAC",
|
||||||
|
Codec: "FLAC",
|
||||||
|
Quality: "HI_RES",
|
||||||
|
BitDepth: 24,
|
||||||
|
SamplingRate: "96",
|
||||||
|
}
|
||||||
|
case 27:
|
||||||
|
return provider.AudioProfile{
|
||||||
|
Container: "FLAC",
|
||||||
|
Codec: "FLAC",
|
||||||
|
Quality: "HI_RES",
|
||||||
|
BitDepth: 24,
|
||||||
|
SamplingRate: "192",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if strings.EqualFold(ext, "mp3") {
|
||||||
|
bitrate := 128
|
||||||
|
if requestedQuality >= 1 {
|
||||||
|
bitrate = 320
|
||||||
|
}
|
||||||
|
return provider.AudioProfile{
|
||||||
|
Container: "MP3",
|
||||||
|
Codec: "MP3",
|
||||||
|
Quality: "HIGH",
|
||||||
|
BitDepth: 16,
|
||||||
|
SamplingRate: "44.1",
|
||||||
|
BitrateKbps: bitrate,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
quality := "LOSSLESS"
|
||||||
|
bitDepth := 16
|
||||||
|
sampling := "44.1"
|
||||||
|
if requestedQuality >= 4 {
|
||||||
|
quality = "HI_RES"
|
||||||
|
bitDepth = 24
|
||||||
|
sampling = "192"
|
||||||
|
} else if requestedQuality >= 3 {
|
||||||
|
quality = "HI_RES"
|
||||||
|
bitDepth = 24
|
||||||
|
sampling = "96"
|
||||||
|
}
|
||||||
|
return provider.AudioProfile{
|
||||||
|
Container: "FLAC",
|
||||||
|
Codec: "FLAC",
|
||||||
|
Quality: quality,
|
||||||
|
BitDepth: bitDepth,
|
||||||
|
SamplingRate: sampling,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func (c *Client) Close() error {
|
func (c *Client) Close() error {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (c *Client) DownloadTrackFallback(ctx context.Context, trackID string, quality int, outputPath string) error {
|
||||||
|
q := &c.cfg.Session.Qobuz
|
||||||
|
if strings.TrimSpace(q.EmailOrUserID) == "" || strings.TrimSpace(q.PasswordOrToken) == "" || q.UseAuthToken {
|
||||||
|
return errors.New("qobuz mobile fallback requires email/password credentials")
|
||||||
|
}
|
||||||
|
if quality < 1 || quality > 4 {
|
||||||
|
quality = q.Quality
|
||||||
|
}
|
||||||
|
formatID := qualityMap(quality)
|
||||||
|
|
||||||
|
if err := c.ensureMobileSession(ctx); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
fileURL, err := c.mobileGetFileURL(ctx, trackID, formatID)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err = os.MkdirAll(filepath.Dir(outputPath), 0o755); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
out, err := os.Create(outputPath)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
success := false
|
||||||
|
defer func() {
|
||||||
|
_ = out.Close()
|
||||||
|
if !success {
|
||||||
|
_ = os.Remove(outputPath)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
progress := mpb.New(mpb.WithWidth(40), mpb.WithOutput(os.Stderr))
|
||||||
|
defer progress.Wait()
|
||||||
|
desc := shortenName(filepath.Base(outputPath), 54)
|
||||||
|
bar := progress.AddSpinner(
|
||||||
|
0,
|
||||||
|
mpb.PrependDecorators(
|
||||||
|
decor.Name(desc+" ", decor.WC{W: 56, C: decor.DSyncWidth | decor.DindentRight}),
|
||||||
|
),
|
||||||
|
mpb.AppendDecorators(
|
||||||
|
decor.CurrentKibiByte("% .1f", decor.WCSyncWidthR),
|
||||||
|
decor.Name(" | ", decor.WCSyncWidth),
|
||||||
|
decor.Elapsed(decor.ET_STYLE_GO, decor.WCSyncWidthR),
|
||||||
|
),
|
||||||
|
mpb.BarRemoveOnComplete(),
|
||||||
|
)
|
||||||
|
defer func() {
|
||||||
|
if !success {
|
||||||
|
bar.Abort(true)
|
||||||
|
}
|
||||||
|
bar.SetTotal(-1, true)
|
||||||
|
}()
|
||||||
|
|
||||||
|
if strings.TrimSpace(fileURL.URL) != "" && fileURL.NSegments == 0 {
|
||||||
|
err = c.mobileCopyURLToWriter(ctx, strings.TrimSpace(fileURL.URL), out, bar)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
success = true
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(fileURL.URLTemplate) == "" {
|
||||||
|
return errors.New("qobuz mobile fallback: no download URL available")
|
||||||
|
}
|
||||||
|
|
||||||
|
var trackKey []byte
|
||||||
|
if strings.TrimSpace(fileURL.Key) != "" {
|
||||||
|
trackKey, err = c.mobileDeriveTrackKey(fileURL.Key)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("derive mobile track key: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
nSegs := fileURL.NSegments
|
||||||
|
if nSegs == 0 {
|
||||||
|
nSegs = 1
|
||||||
|
}
|
||||||
|
initURL := strings.Replace(fileURL.URLTemplate, "$SEGMENT$", "0", 1)
|
||||||
|
initData, err := c.mobileDownloadSegment(ctx, initURL)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("download init segment: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if hdr := extractFLACHeader(initData); hdr != nil {
|
||||||
|
if _, err = out.Write(hdr); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
bar.IncrBy(len(hdr))
|
||||||
|
} else {
|
||||||
|
if _, err = out.Write(initData); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
bar.IncrBy(len(initData))
|
||||||
|
}
|
||||||
|
|
||||||
|
for seg := 1; seg <= nSegs; seg++ {
|
||||||
|
segURL := strings.Replace(fileURL.URLTemplate, "$SEGMENT$", strconv.Itoa(seg), 1)
|
||||||
|
data, dlErr := c.mobileDownloadSegment(ctx, segURL)
|
||||||
|
if dlErr != nil {
|
||||||
|
return fmt.Errorf("download segment %d: %w", seg, dlErr)
|
||||||
|
}
|
||||||
|
frames := extractFrames(data, trackKey)
|
||||||
|
if _, err = out.Write(frames); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
bar.IncrBy(len(frames))
|
||||||
|
}
|
||||||
|
if err = out.Sync(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
success = true
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
func (c *Client) getPlaylist(ctx context.Context, playlistID string) (map[string]any, error) {
|
func (c *Client) getPlaylist(ctx context.Context, playlistID string) (map[string]any, error) {
|
||||||
pageLimit := 500
|
pageLimit := 500
|
||||||
params := url.Values{}
|
params := url.Values{}
|
||||||
@@ -694,7 +931,7 @@ func (c *Client) fetchAppIDAndSecrets(ctx context.Context) (string, []string, er
|
|||||||
|
|
||||||
tzNames := make([]string, 0, len(ordered))
|
tzNames := make([]string, 0, len(ordered))
|
||||||
for _, o := range ordered {
|
for _, o := range ordered {
|
||||||
tzNames = append(tzNames, strings.Title(o.timezone))
|
tzNames = append(tzNames, jsonutil.TitleCase(o.timezone))
|
||||||
}
|
}
|
||||||
infoRe := regexp.MustCompile(fmt.Sprintf(infoExtrasTemplate, strings.Join(tzNames, "|")))
|
infoRe := regexp.MustCompile(fmt.Sprintf(infoExtrasTemplate, strings.Join(tzNames, "|")))
|
||||||
idxInfo := infoRe.SubexpIndex("info")
|
idxInfo := infoRe.SubexpIndex("info")
|
||||||
@@ -742,3 +979,460 @@ func sortedKeys(m map[string][]string) []string {
|
|||||||
sort.Strings(keys)
|
sort.Strings(keys)
|
||||||
return keys
|
return keys
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (c *Client) ensureMobileSession(ctx context.Context) error {
|
||||||
|
c.mobileMu.Lock()
|
||||||
|
defer c.mobileMu.Unlock()
|
||||||
|
if c.mobileAccessToken != "" && c.mobileSessionID != "" && c.mobileSessionInfo != "" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
q := &c.cfg.Session.Qobuz
|
||||||
|
if err := c.mobileLogin(ctx, q.EmailOrUserID, q.PasswordOrToken); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := c.mobileStartSession(ctx); err != nil {
|
||||||
|
c.mobileAccessToken = ""
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) mobileLogin(ctx context.Context, username, password string) error {
|
||||||
|
ts := time.Now().Unix()
|
||||||
|
params := url.Values{}
|
||||||
|
params.Set("app_id", mobileAppID)
|
||||||
|
params.Set("username", username)
|
||||||
|
params.Set("password", password)
|
||||||
|
params.Set("request_ts", strconv.FormatInt(ts, 10))
|
||||||
|
params.Set("request_sig", mobileSignRequest("oauth2/login", []kv{{"password", password}, {"username", username}}, ts))
|
||||||
|
|
||||||
|
reqURL := baseURL + "/oauth2/login?" + params.Encode()
|
||||||
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, reqURL, nil)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
c.setMobileHeaders(req)
|
||||||
|
resp, err := c.http.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("mobile login request failed: %w", err)
|
||||||
|
}
|
||||||
|
defer func() { _ = resp.Body.Close() }()
|
||||||
|
body, err := io.ReadAll(resp.Body)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if resp.StatusCode != http.StatusOK {
|
||||||
|
return fmt.Errorf("mobile login failed: status=%d body=%s", resp.StatusCode, string(body))
|
||||||
|
}
|
||||||
|
var parsed struct {
|
||||||
|
OAuth2 struct {
|
||||||
|
AccessToken string `json:"access_token"`
|
||||||
|
} `json:"oauth2"`
|
||||||
|
}
|
||||||
|
if err = json.Unmarshal(body, &parsed); err != nil {
|
||||||
|
return fmt.Errorf("mobile login parse failed: %w", err)
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(parsed.OAuth2.AccessToken) == "" {
|
||||||
|
return errors.New("mobile login returned empty token")
|
||||||
|
}
|
||||||
|
c.mobileAccessToken = strings.TrimSpace(parsed.OAuth2.AccessToken)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) mobileStartSession(ctx context.Context) error {
|
||||||
|
ts := time.Now().Unix()
|
||||||
|
params := url.Values{}
|
||||||
|
params.Set("app_id", mobileAppID)
|
||||||
|
params.Set("request_ts", strconv.FormatInt(ts, 10))
|
||||||
|
params.Set("request_sig", mobileSignRequest("session/start", []kv{{"profile", mobileSessionProf}}, ts))
|
||||||
|
|
||||||
|
reqURL := baseURL + "/session/start?" + params.Encode()
|
||||||
|
form := url.Values{}
|
||||||
|
form.Set("profile", mobileSessionProf)
|
||||||
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, reqURL, strings.NewReader(form.Encode()))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||||
|
c.setMobileHeaders(req)
|
||||||
|
resp, err := c.http.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("mobile session request failed: %w", err)
|
||||||
|
}
|
||||||
|
defer func() { _ = resp.Body.Close() }()
|
||||||
|
body, err := io.ReadAll(resp.Body)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if resp.StatusCode != http.StatusOK {
|
||||||
|
return fmt.Errorf("mobile session start failed: status=%d body=%s", resp.StatusCode, string(body))
|
||||||
|
}
|
||||||
|
var parsed struct {
|
||||||
|
SessionID string `json:"session_id"`
|
||||||
|
Infos string `json:"infos"`
|
||||||
|
}
|
||||||
|
if err = json.Unmarshal(body, &parsed); err != nil {
|
||||||
|
return fmt.Errorf("mobile session parse failed: %w", err)
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(parsed.SessionID) == "" || strings.TrimSpace(parsed.Infos) == "" {
|
||||||
|
return errors.New("mobile session start returned incomplete session data")
|
||||||
|
}
|
||||||
|
c.mobileSessionID = strings.TrimSpace(parsed.SessionID)
|
||||||
|
c.mobileSessionInfo = strings.TrimSpace(parsed.Infos)
|
||||||
|
c.mobileKEK = nil
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) mobileGetFileURL(ctx context.Context, trackID string, formatID int) (*mobileFileURL, error) {
|
||||||
|
ts := time.Now().Unix()
|
||||||
|
params := url.Values{}
|
||||||
|
params.Set("app_id", mobileAppID)
|
||||||
|
params.Set("track_id", trackID)
|
||||||
|
params.Set("format_id", strconv.Itoa(formatID))
|
||||||
|
params.Set("intent", "stream")
|
||||||
|
params.Set("request_ts", strconv.FormatInt(ts, 10))
|
||||||
|
params.Set("request_sig", mobileSignRequest("file/url", []kv{{"format_id", strconv.Itoa(formatID)}, {"intent", "stream"}, {"track_id", trackID}}, ts))
|
||||||
|
reqURL := baseURL + "/file/url?" + params.Encode()
|
||||||
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, reqURL, nil)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
c.setMobileHeaders(req)
|
||||||
|
resp, err := c.http.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer func() { _ = resp.Body.Close() }()
|
||||||
|
body, err := io.ReadAll(resp.Body)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if resp.StatusCode != http.StatusOK {
|
||||||
|
return nil, fmt.Errorf("mobile file url failed: status=%d body=%s", resp.StatusCode, string(body))
|
||||||
|
}
|
||||||
|
var parsed mobileFileURL
|
||||||
|
if err = json.Unmarshal(body, &parsed); err != nil {
|
||||||
|
return nil, fmt.Errorf("mobile file url parse failed: %w", err)
|
||||||
|
}
|
||||||
|
return &parsed, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) mobileCopyURLToWriter(ctx context.Context, sourceURL string, out io.Writer, bar *mpb.Bar) error {
|
||||||
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, sourceURL, nil)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
c.setMobileHeaders(req)
|
||||||
|
resp, err := c.http.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer func() { _ = resp.Body.Close() }()
|
||||||
|
if resp.StatusCode != http.StatusOK {
|
||||||
|
return fmt.Errorf("mobile fallback download failed: status=%d", resp.StatusCode)
|
||||||
|
}
|
||||||
|
written, err := io.Copy(out, &countingReader{r: resp.Body, onRead: func(n int) {
|
||||||
|
if bar != nil && n > 0 {
|
||||||
|
bar.IncrBy(n)
|
||||||
|
}
|
||||||
|
}})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if resp.ContentLength > 0 && written != resp.ContentLength {
|
||||||
|
return io.ErrUnexpectedEOF
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type countingReader struct {
|
||||||
|
r io.Reader
|
||||||
|
onRead func(int)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *countingReader) Read(p []byte) (int, error) {
|
||||||
|
n, err := c.r.Read(p)
|
||||||
|
if n > 0 && c.onRead != nil {
|
||||||
|
c.onRead(n)
|
||||||
|
}
|
||||||
|
return n, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func shortenName(name string, max int) string {
|
||||||
|
if max <= 0 {
|
||||||
|
return name
|
||||||
|
}
|
||||||
|
r := []rune(name)
|
||||||
|
if len(r) <= max {
|
||||||
|
return name
|
||||||
|
}
|
||||||
|
if max <= 3 {
|
||||||
|
return string(r[:max])
|
||||||
|
}
|
||||||
|
return string(r[:max-3]) + "..."
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) mobileDownloadSegment(ctx context.Context, sourceURL string) ([]byte, error) {
|
||||||
|
var lastErr error
|
||||||
|
for attempt := 0; attempt < mobileSegmentTries; attempt++ {
|
||||||
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, sourceURL, nil)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
c.setMobileHeaders(req)
|
||||||
|
resp, err := c.http.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
lastErr = err
|
||||||
|
time.Sleep(time.Duration(500*(attempt+1)) * time.Millisecond)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if resp.StatusCode != http.StatusOK {
|
||||||
|
lastErr = fmt.Errorf("status=%d", resp.StatusCode)
|
||||||
|
_ = resp.Body.Close()
|
||||||
|
time.Sleep(time.Duration(500*(attempt+1)) * time.Millisecond)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
data, readErr := io.ReadAll(resp.Body)
|
||||||
|
_ = resp.Body.Close()
|
||||||
|
if readErr != nil {
|
||||||
|
lastErr = readErr
|
||||||
|
time.Sleep(time.Duration(500*(attempt+1)) * time.Millisecond)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
return data, nil
|
||||||
|
}
|
||||||
|
if lastErr == nil {
|
||||||
|
lastErr = errors.New("unknown segment error")
|
||||||
|
}
|
||||||
|
return nil, fmt.Errorf("mobile segment download failed after retries: %w", lastErr)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) setMobileHeaders(req *http.Request) {
|
||||||
|
req.Header.Set("User-Agent", mobileUserAgent)
|
||||||
|
req.Header.Set("X-App-Id", mobileAppID)
|
||||||
|
req.Header.Set("X-App-Version", mobileAppVersion)
|
||||||
|
req.Header.Set("X-Device-Platform", "android")
|
||||||
|
req.Header.Set("X-Device-Model", "Nexus 6P")
|
||||||
|
req.Header.Set("X-Device-Os-Version", "9")
|
||||||
|
if c.mobileAccessToken != "" {
|
||||||
|
req.Header.Set("Authorization", "Bearer "+c.mobileAccessToken)
|
||||||
|
}
|
||||||
|
if c.mobileSessionID != "" {
|
||||||
|
req.Header.Set("X-Session-Id", c.mobileSessionID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func mobileSignRequest(endpoint string, params []kv, ts int64) string {
|
||||||
|
method := strings.ReplaceAll(endpoint, "/", "")
|
||||||
|
sortKVs(params)
|
||||||
|
var sb strings.Builder
|
||||||
|
sb.WriteString(method)
|
||||||
|
for _, p := range params {
|
||||||
|
sb.WriteString(p.Key)
|
||||||
|
sb.WriteString(p.Value)
|
||||||
|
}
|
||||||
|
sb.WriteString(strconv.FormatInt(ts, 10))
|
||||||
|
sb.WriteString(mobileAppSecret)
|
||||||
|
h := md5.Sum([]byte(sb.String()))
|
||||||
|
return hex.EncodeToString(h[:])
|
||||||
|
}
|
||||||
|
|
||||||
|
type kv struct {
|
||||||
|
Key string
|
||||||
|
Value string
|
||||||
|
}
|
||||||
|
|
||||||
|
func sortKVs(s []kv) {
|
||||||
|
for i := 0; i < len(s); i++ {
|
||||||
|
for j := i + 1; j < len(s); j++ {
|
||||||
|
if s[j].Key < s[i].Key {
|
||||||
|
s[i], s[j] = s[j], s[i]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) mobileDeriveTrackKey(encryptedKey string) ([]byte, error) {
|
||||||
|
if len(c.mobileKEK) == 16 {
|
||||||
|
return unwrapQobuzTrackKey(encryptedKey, c.mobileKEK)
|
||||||
|
}
|
||||||
|
parts := strings.SplitN(c.mobileSessionInfo, ".", 2)
|
||||||
|
if len(parts) != 2 {
|
||||||
|
return nil, errors.New("invalid mobile session infos format")
|
||||||
|
}
|
||||||
|
salt, err := base64.RawURLEncoding.DecodeString(parts[0])
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("decode mobile salt: %w", err)
|
||||||
|
}
|
||||||
|
info, err := base64.RawURLEncoding.DecodeString(parts[1])
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("decode mobile info: %w", err)
|
||||||
|
}
|
||||||
|
reader := hkdf.New(func() hash.Hash { return sha256.New() }, hexDecodeOrNil(mobileAppSecret), salt, info)
|
||||||
|
kek := make([]byte, 16)
|
||||||
|
if _, err = io.ReadFull(reader, kek); err != nil {
|
||||||
|
return nil, fmt.Errorf("mobile hkdf derive failed: %w", err)
|
||||||
|
}
|
||||||
|
c.mobileKEK = kek
|
||||||
|
return unwrapQobuzTrackKey(encryptedKey, kek)
|
||||||
|
}
|
||||||
|
|
||||||
|
func hexDecodeOrNil(s string) []byte {
|
||||||
|
b, _ := hex.DecodeString(s)
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
func unwrapQobuzTrackKey(encryptedKey string, kek []byte) ([]byte, error) {
|
||||||
|
parts := strings.SplitN(encryptedKey, ".", 3)
|
||||||
|
if len(parts) != 3 || parts[0] != mobileSessionProf {
|
||||||
|
return nil, errors.New("invalid qobuz track key format")
|
||||||
|
}
|
||||||
|
encKey, err := base64.RawURLEncoding.DecodeString(parts[1])
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("decode encrypted key failed: %w", err)
|
||||||
|
}
|
||||||
|
iv, err := base64.RawURLEncoding.DecodeString(parts[2])
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("decode key iv failed: %w", err)
|
||||||
|
}
|
||||||
|
block, err := aes.NewCipher(kek)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
decrypted := make([]byte, len(encKey))
|
||||||
|
mode := cipher.NewCBCDecrypter(block, iv)
|
||||||
|
mode.CryptBlocks(decrypted, encKey)
|
||||||
|
if len(decrypted) < 16 {
|
||||||
|
return nil, errors.New("decrypted key too short")
|
||||||
|
}
|
||||||
|
return decrypted[:16], nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func extractFLACHeader(data []byte) []byte {
|
||||||
|
blocks := findDFLABlocks(data)
|
||||||
|
if blocks == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
out := make([]byte, 4+len(blocks))
|
||||||
|
copy(out, "fLaC")
|
||||||
|
copy(out[4:], blocks)
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func findDFLABlocks(data []byte) []byte {
|
||||||
|
pos := 0
|
||||||
|
for pos+8 <= len(data) {
|
||||||
|
size := int(uint32(data[pos])<<24 | uint32(data[pos+1])<<16 | uint32(data[pos+2])<<8 | uint32(data[pos+3]))
|
||||||
|
if size < 8 || pos+size > len(data) {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
t := data[pos+4 : pos+8]
|
||||||
|
if string(t) == "dfLa" {
|
||||||
|
body := data[pos+8 : pos+size]
|
||||||
|
if len(body) > 4 {
|
||||||
|
return body[4:]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var inner []byte
|
||||||
|
switch string(t) {
|
||||||
|
case "moov", "trak", "mdia", "minf", "stbl":
|
||||||
|
inner = data[pos+8 : pos+size]
|
||||||
|
case "stsd":
|
||||||
|
if pos+16 <= pos+size {
|
||||||
|
inner = data[pos+16 : pos+size]
|
||||||
|
}
|
||||||
|
case "fLaC":
|
||||||
|
if pos+36 <= pos+size {
|
||||||
|
inner = data[pos+36 : pos+size]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if inner != nil {
|
||||||
|
if result := findDFLABlocks(inner); result != nil {
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pos += size
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func extractFrames(data []byte, key []byte) []byte {
|
||||||
|
var frames []byte
|
||||||
|
pos := 0
|
||||||
|
for pos+8 <= len(data) {
|
||||||
|
boxSize := int(uint32(data[pos])<<24 | uint32(data[pos+1])<<16 | uint32(data[pos+2])<<8 | uint32(data[pos+3]))
|
||||||
|
if boxSize < 8 || pos+boxSize > len(data) {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if string(data[pos+4:pos+8]) == "uuid" && boxSize >= 36 {
|
||||||
|
if pos+24 > len(data) {
|
||||||
|
pos += boxSize
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if bytes.Equal(data[pos+8:pos+24], qobuzUUIDBytes) {
|
||||||
|
f := parseUUIDBox(data, pos, boxSize, key)
|
||||||
|
frames = append(frames, f...)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pos += boxSize
|
||||||
|
}
|
||||||
|
return frames
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseUUIDBox(data []byte, boxStart, boxSize int, key []byte) []byte {
|
||||||
|
bodyOff := boxStart + 24
|
||||||
|
if bodyOff+12 > len(data) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
rawOffset := readU32BE(data, bodyOff+4)
|
||||||
|
numSamples := int(readU24BE(data, bodyOff+9))
|
||||||
|
if numSamples == 0 || numSamples > 10000 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
tableOff := bodyOff + 12
|
||||||
|
sampleDataOff := boxStart + int(rawOffset)
|
||||||
|
var frames []byte
|
||||||
|
offset := sampleDataOff
|
||||||
|
for i := 0; i < numSamples; i++ {
|
||||||
|
et := tableOff + i*16
|
||||||
|
if et+16 > len(data) || offset >= len(data) {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
size := readU32BE(data, et)
|
||||||
|
encFlag := data[et+6] != 0 || data[et+7] != 0
|
||||||
|
end := offset + int(size)
|
||||||
|
if end > len(data) {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if encFlag && len(key) == 16 {
|
||||||
|
iv := make([]byte, 16)
|
||||||
|
copy(iv[:8], data[et+8:et+16])
|
||||||
|
block, err := aes.NewCipher(key)
|
||||||
|
if err != nil {
|
||||||
|
return frames
|
||||||
|
}
|
||||||
|
stream := cipher.NewCTR(block, iv)
|
||||||
|
decrypted := make([]byte, end-offset)
|
||||||
|
stream.XORKeyStream(decrypted, data[offset:end])
|
||||||
|
frames = append(frames, decrypted...)
|
||||||
|
} else {
|
||||||
|
frames = append(frames, data[offset:end]...)
|
||||||
|
}
|
||||||
|
offset = end
|
||||||
|
}
|
||||||
|
return frames
|
||||||
|
}
|
||||||
|
|
||||||
|
func readU32BE(data []byte, off int) uint32 {
|
||||||
|
if off+4 > len(data) {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
return uint32(data[off])<<24 | uint32(data[off+1])<<16 | uint32(data[off+2])<<8 | uint32(data[off+3])
|
||||||
|
}
|
||||||
|
|
||||||
|
func readU24BE(data []byte, off int) uint32 {
|
||||||
|
if off+3 > len(data) {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
return uint32(data[off])<<16 | uint32(data[off+1])<<8 | uint32(data[off+2])
|
||||||
|
}
|
||||||
|
|||||||
@@ -366,6 +366,9 @@ func TestGetDownloadableUsesReturnedURLExtension(t *testing.T) {
|
|||||||
if d.Extension != "mp3" {
|
if d.Extension != "mp3" {
|
||||||
t.Fatalf("extension = %q, want mp3", d.Extension)
|
t.Fatalf("extension = %q, want mp3", d.Extension)
|
||||||
}
|
}
|
||||||
|
if d.Audio.Container != "MP3" || d.Audio.Codec != "MP3" {
|
||||||
|
t.Fatalf("unexpected audio profile: %+v", d.Audio)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func qobuzSecretSig(requestTS, secret string) string {
|
func qobuzSecretSig(requestTS, secret string) string {
|
||||||
|
|||||||
@@ -10,12 +10,12 @@ import (
|
|||||||
"net/url"
|
"net/url"
|
||||||
"os/exec"
|
"os/exec"
|
||||||
"regexp"
|
"regexp"
|
||||||
"strconv"
|
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"streamrip-go/internal/config"
|
"streamrip-go/internal/config"
|
||||||
|
"streamrip-go/internal/jsonutil"
|
||||||
"streamrip-go/internal/provider"
|
"streamrip-go/internal/provider"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -102,14 +102,14 @@ func (c *Client) searchTracks(ctx context.Context, query string, limit int) ([]m
|
|||||||
if id == "" {
|
if id == "" {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
artist := strings.TrimSpace(stringFromAny(m["uploader"]))
|
artist := strings.TrimSpace(jsonutil.StringFromAny(m["uploader"]))
|
||||||
if artist == "" {
|
if artist == "" {
|
||||||
artist = strings.TrimSpace(stringFromAny(m["channel"]))
|
artist = strings.TrimSpace(jsonutil.StringFromAny(m["channel"]))
|
||||||
}
|
}
|
||||||
artistID := strings.TrimSpace(firstNonEmpty(stringFromAny(m["uploader_id"]), stringFromAny(m["channel_id"])))
|
artistID := strings.TrimSpace(jsonutil.FirstNonEmpty(jsonutil.StringFromAny(m["uploader_id"]), jsonutil.StringFromAny(m["channel_id"])))
|
||||||
item := map[string]any{
|
item := map[string]any{
|
||||||
"id": id,
|
"id": id,
|
||||||
"title": stringFromAny(m["title"]),
|
"title": jsonutil.StringFromAny(m["title"]),
|
||||||
"artist": map[string]any{
|
"artist": map[string]any{
|
||||||
"name": artist,
|
"name": artist,
|
||||||
},
|
},
|
||||||
@@ -117,7 +117,7 @@ func (c *Client) searchTracks(ctx context.Context, query string, limit int) ([]m
|
|||||||
if artistID != "" {
|
if artistID != "" {
|
||||||
item["artist"] = map[string]any{"name": artist, "id": artistID}
|
item["artist"] = map[string]any{"name": artist, "id": artistID}
|
||||||
}
|
}
|
||||||
if trackID := strings.TrimSpace(stringFromAny(m["id"])); trackID != "" {
|
if trackID := strings.TrimSpace(jsonutil.StringFromAny(m["id"])); trackID != "" {
|
||||||
item["source_track_id"] = trackID
|
item["source_track_id"] = trackID
|
||||||
}
|
}
|
||||||
items = append(items, item)
|
items = append(items, item)
|
||||||
@@ -163,17 +163,17 @@ func (c *Client) searchPlaylists(ctx context.Context, query string, limit int) (
|
|||||||
if infoErr != nil {
|
if infoErr != nil {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
title := strings.TrimSpace(stringFromAny(info["title"]))
|
title := strings.TrimSpace(jsonutil.StringFromAny(info["title"]))
|
||||||
if title == "" {
|
if title == "" {
|
||||||
title = strings.Trim(strings.ReplaceAll(path, "/", " "), " ")
|
title = strings.Trim(strings.ReplaceAll(path, "/", " "), " ")
|
||||||
}
|
}
|
||||||
artist := strings.TrimSpace(firstNonEmpty(stringFromAny(info["uploader"]), stringFromAny(info["channel"])))
|
artist := strings.TrimSpace(jsonutil.FirstNonEmpty(jsonutil.StringFromAny(info["uploader"]), jsonutil.StringFromAny(info["channel"])))
|
||||||
artistID := strings.TrimSpace(firstNonEmpty(stringFromAny(info["uploader_id"]), stringFromAny(info["channel_id"])))
|
artistID := strings.TrimSpace(jsonutil.FirstNonEmpty(jsonutil.StringFromAny(info["uploader_id"]), jsonutil.StringFromAny(info["channel_id"])))
|
||||||
trackCount := 0
|
trackCount := 0
|
||||||
if entries := asAnySlice(info["entries"]); len(entries) > 0 {
|
if entries := asAnySlice(info["entries"]); len(entries) > 0 {
|
||||||
trackCount = len(entries)
|
trackCount = len(entries)
|
||||||
}
|
}
|
||||||
canonical := firstNonEmpty(canonicalSoundcloudURL(info), playlistURL)
|
canonical := jsonutil.FirstNonEmpty(canonicalSoundcloudURL(info), playlistURL)
|
||||||
item := map[string]any{
|
item := map[string]any{
|
||||||
"id": canonical,
|
"id": canonical,
|
||||||
"title": title,
|
"title": title,
|
||||||
@@ -183,10 +183,10 @@ func (c *Client) searchPlaylists(ctx context.Context, query string, limit int) (
|
|||||||
if artistID != "" {
|
if artistID != "" {
|
||||||
item["artist"] = map[string]any{"name": artist, "id": artistID}
|
item["artist"] = map[string]any{"name": artist, "id": artistID}
|
||||||
}
|
}
|
||||||
if pid := strings.TrimSpace(stringFromAny(info["id"])); pid != "" {
|
if pid := strings.TrimSpace(jsonutil.StringFromAny(info["id"])); pid != "" {
|
||||||
item["source_playlist_id"] = pid
|
item["source_playlist_id"] = pid
|
||||||
}
|
}
|
||||||
if thumb := strings.TrimSpace(stringFromAny(info["thumbnail"])); thumb != "" {
|
if thumb := strings.TrimSpace(jsonutil.StringFromAny(info["thumbnail"])); thumb != "" {
|
||||||
item["image"] = soundcloudImageMap(thumb)
|
item["image"] = soundcloudImageMap(thumb)
|
||||||
}
|
}
|
||||||
items = append(items, item)
|
items = append(items, item)
|
||||||
@@ -228,15 +228,15 @@ func (c *Client) GetMetadata(ctx context.Context, item, mediaType string) (map[s
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
track := map[string]any{"id": id}
|
track := map[string]any{"id": id}
|
||||||
if trackID := strings.TrimSpace(stringFromAny(entry["id"])); trackID != "" {
|
if trackID := strings.TrimSpace(jsonutil.StringFromAny(entry["id"])); trackID != "" {
|
||||||
track["source_track_id"] = trackID
|
track["source_track_id"] = trackID
|
||||||
}
|
}
|
||||||
if title := strings.TrimSpace(stringFromAny(entry["title"])); title != "" {
|
if title := strings.TrimSpace(jsonutil.StringFromAny(entry["title"])); title != "" {
|
||||||
track["title"] = title
|
track["title"] = title
|
||||||
}
|
}
|
||||||
if artist := strings.TrimSpace(firstNonEmpty(stringFromAny(entry["uploader"]), stringFromAny(entry["channel"]))); artist != "" {
|
if artist := strings.TrimSpace(jsonutil.FirstNonEmpty(jsonutil.StringFromAny(entry["uploader"]), jsonutil.StringFromAny(entry["channel"]))); artist != "" {
|
||||||
artistMap := map[string]any{"name": artist}
|
artistMap := map[string]any{"name": artist}
|
||||||
if artistID := strings.TrimSpace(firstNonEmpty(stringFromAny(entry["uploader_id"]), stringFromAny(entry["channel_id"]))); artistID != "" {
|
if artistID := strings.TrimSpace(jsonutil.FirstNonEmpty(jsonutil.StringFromAny(entry["uploader_id"]), jsonutil.StringFromAny(entry["channel_id"]))); artistID != "" {
|
||||||
artistMap["id"] = artistID
|
artistMap["id"] = artistID
|
||||||
}
|
}
|
||||||
track["artist"] = artistMap
|
track["artist"] = artistMap
|
||||||
@@ -244,23 +244,23 @@ func (c *Client) GetMetadata(ctx context.Context, item, mediaType string) (map[s
|
|||||||
track["track_number"] = i + 1
|
track["track_number"] = i + 1
|
||||||
tracks = append(tracks, track)
|
tracks = append(tracks, track)
|
||||||
}
|
}
|
||||||
name := strings.TrimSpace(stringFromAny(root["title"]))
|
name := strings.TrimSpace(jsonutil.StringFromAny(root["title"]))
|
||||||
if name == "" {
|
if name == "" {
|
||||||
name = "SoundCloud Playlist"
|
name = "SoundCloud Playlist"
|
||||||
}
|
}
|
||||||
meta := map[string]any{
|
meta := map[string]any{
|
||||||
"id": firstNonEmpty(canonicalSoundcloudURL(root), item),
|
"id": jsonutil.FirstNonEmpty(canonicalSoundcloudURL(root), item),
|
||||||
"name": name,
|
"name": name,
|
||||||
"description": strings.TrimSpace(stringFromAny(root["description"])),
|
"description": strings.TrimSpace(jsonutil.StringFromAny(root["description"])),
|
||||||
"tracks": map[string]any{"items": tracks},
|
"tracks": map[string]any{"items": tracks},
|
||||||
}
|
}
|
||||||
if pid := strings.TrimSpace(stringFromAny(root["id"])); pid != "" {
|
if pid := strings.TrimSpace(jsonutil.StringFromAny(root["id"])); pid != "" {
|
||||||
meta["source_playlist_id"] = pid
|
meta["source_playlist_id"] = pid
|
||||||
}
|
}
|
||||||
if artist := strings.TrimSpace(firstNonEmpty(stringFromAny(root["uploader"]), stringFromAny(root["channel"]))); artist != "" {
|
if artist := strings.TrimSpace(jsonutil.FirstNonEmpty(jsonutil.StringFromAny(root["uploader"]), jsonutil.StringFromAny(root["channel"]))); artist != "" {
|
||||||
meta["artist"] = map[string]any{"name": artist}
|
meta["artist"] = map[string]any{"name": artist}
|
||||||
}
|
}
|
||||||
if thumb := strings.TrimSpace(stringFromAny(root["thumbnail"])); thumb != "" {
|
if thumb := strings.TrimSpace(jsonutil.StringFromAny(root["thumbnail"])); thumb != "" {
|
||||||
meta["image"] = soundcloudImageMap(thumb)
|
meta["image"] = soundcloudImageMap(thumb)
|
||||||
}
|
}
|
||||||
if entries := asAnySlice(root["entries"]); len(entries) > 0 {
|
if entries := asAnySlice(root["entries"]); len(entries) > 0 {
|
||||||
@@ -280,21 +280,38 @@ func (c *Client) GetDownloadable(ctx context.Context, item string, _ int) (*prov
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
streamURL := strings.TrimSpace(stringFromAny(info["url"]))
|
streamURL := strings.TrimSpace(jsonutil.StringFromAny(info["url"]))
|
||||||
if streamURL == "" {
|
if streamURL == "" {
|
||||||
return nil, errors.New("yt-dlp output missing url (track may be unavailable or region-restricted)")
|
return nil, errors.New("yt-dlp output missing url (track may be unavailable or region-restricted)")
|
||||||
}
|
}
|
||||||
ext := strings.TrimSpace(stringFromAny(info["ext"]))
|
ext := strings.TrimSpace(jsonutil.StringFromAny(info["ext"]))
|
||||||
if ext == "" {
|
if ext == "" {
|
||||||
ext = "m4a"
|
ext = "m4a"
|
||||||
}
|
}
|
||||||
return &provider.Downloadable{URL: streamURL, Extension: ext, Source: "soundcloud"}, nil
|
return &provider.Downloadable{URL: streamURL, Extension: ext, Source: "soundcloud", Audio: soundcloudAudioProfile(ext)}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Client) Close() error {
|
func (c *Client) Close() error {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func soundcloudAudioProfile(ext string) provider.AudioProfile {
|
||||||
|
switch strings.ToLower(strings.TrimSpace(ext)) {
|
||||||
|
case "mp3":
|
||||||
|
return provider.AudioProfile{Container: "MP3", Codec: "MP3", Quality: "LOSSY", BitDepth: 16, SamplingRate: "44.1"}
|
||||||
|
case "flac":
|
||||||
|
return provider.AudioProfile{Container: "FLAC", Codec: "FLAC", Quality: "LOSSLESS", BitDepth: 16, SamplingRate: "44.1"}
|
||||||
|
case "m4a", "aac":
|
||||||
|
return provider.AudioProfile{Container: "M4A", Codec: "AAC", Quality: "LOSSY", BitDepth: 16, SamplingRate: "44.1"}
|
||||||
|
default:
|
||||||
|
container := strings.ToUpper(strings.TrimSpace(ext))
|
||||||
|
if container == "" {
|
||||||
|
container = "M4A"
|
||||||
|
}
|
||||||
|
return provider.AudioProfile{Container: container, Codec: container, Quality: "LOSSY", BitDepth: 16, SamplingRate: "44.1"}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func (c *Client) trackInfo(ctx context.Context, item string) (map[string]any, error) {
|
func (c *Client) trackInfo(ctx context.Context, item string) (map[string]any, error) {
|
||||||
if strings.TrimSpace(item) == "" {
|
if strings.TrimSpace(item) == "" {
|
||||||
return nil, errors.New("empty soundcloud item")
|
return nil, errors.New("empty soundcloud item")
|
||||||
@@ -337,36 +354,36 @@ func (c *Client) playlistInfo(ctx context.Context, item string) (map[string]any,
|
|||||||
}
|
}
|
||||||
|
|
||||||
func trackMetadataFromInfo(id string, info map[string]any) map[string]any {
|
func trackMetadataFromInfo(id string, info map[string]any) map[string]any {
|
||||||
canonicalID := firstNonEmpty(canonicalSoundcloudURL(info), id)
|
canonicalID := jsonutil.FirstNonEmpty(canonicalSoundcloudURL(info), id)
|
||||||
publisher := nestedMap(info, "publisher_metadata")
|
publisher := jsonutil.NestedMap(info, "publisher_metadata")
|
||||||
title := strings.TrimSpace(stringFromAny(info["title"]))
|
title := strings.TrimSpace(jsonutil.StringFromAny(info["title"]))
|
||||||
if title == "" {
|
if title == "" {
|
||||||
title = canonicalID
|
title = canonicalID
|
||||||
}
|
}
|
||||||
albumTitle := strings.TrimSpace(stringFromAny(publisher["album_title"]))
|
albumTitle := strings.TrimSpace(jsonutil.StringFromAny(publisher["album_title"]))
|
||||||
if albumTitle == "" {
|
if albumTitle == "" {
|
||||||
albumTitle = strings.TrimSpace(stringFromAny(info["album"]))
|
albumTitle = strings.TrimSpace(jsonutil.StringFromAny(info["album"]))
|
||||||
}
|
}
|
||||||
if albumTitle == "" {
|
if albumTitle == "" {
|
||||||
albumTitle = title
|
albumTitle = title
|
||||||
}
|
}
|
||||||
artistName := strings.TrimSpace(stringFromAny(info["artist"]))
|
artistName := strings.TrimSpace(jsonutil.StringFromAny(info["artist"]))
|
||||||
if artistName == "" {
|
if artistName == "" {
|
||||||
artistName = strings.TrimSpace(stringFromAny(publisher["artist"]))
|
artistName = strings.TrimSpace(jsonutil.StringFromAny(publisher["artist"]))
|
||||||
}
|
}
|
||||||
if artistName == "" {
|
if artistName == "" {
|
||||||
artistName = strings.TrimSpace(stringFromAny(info["uploader"]))
|
artistName = strings.TrimSpace(jsonutil.StringFromAny(info["uploader"]))
|
||||||
}
|
}
|
||||||
if artistName == "" {
|
if artistName == "" {
|
||||||
artistName = strings.TrimSpace(stringFromAny(info["channel"]))
|
artistName = strings.TrimSpace(jsonutil.StringFromAny(info["channel"]))
|
||||||
}
|
}
|
||||||
artistID := strings.TrimSpace(firstNonEmpty(
|
artistID := strings.TrimSpace(jsonutil.FirstNonEmpty(
|
||||||
stringFromAny(info["uploader_id"]),
|
jsonutil.StringFromAny(info["uploader_id"]),
|
||||||
stringFromAny(info["channel_id"]),
|
jsonutil.StringFromAny(info["channel_id"]),
|
||||||
stringFromAny(nestedMap(info, "user")["id"]),
|
jsonutil.StringFromAny(jsonutil.NestedMap(info, "user")["id"]),
|
||||||
))
|
))
|
||||||
|
|
||||||
trackNum := intFromAny(info["track_number"])
|
trackNum := jsonutil.IntFromAny(info["track_number"])
|
||||||
if trackNum <= 0 {
|
if trackNum <= 0 {
|
||||||
trackNum = 1
|
trackNum = 1
|
||||||
}
|
}
|
||||||
@@ -378,26 +395,26 @@ func trackMetadataFromInfo(id string, info map[string]any) map[string]any {
|
|||||||
"artist": map[string]any{"name": artistName, "id": artistID},
|
"artist": map[string]any{"name": artistName, "id": artistID},
|
||||||
"performer": map[string]any{"name": artistName, "id": artistID},
|
"performer": map[string]any{"name": artistName, "id": artistID},
|
||||||
"album": map[string]any{
|
"album": map[string]any{
|
||||||
"id": firstNonEmpty(strings.TrimSpace(stringFromAny(info["album"])), canonicalID),
|
"id": jsonutil.FirstNonEmpty(strings.TrimSpace(jsonutil.StringFromAny(info["album"])), canonicalID),
|
||||||
"title": albumTitle,
|
"title": albumTitle,
|
||||||
"artist": map[string]any{"name": artistName, "id": artistID},
|
"artist": map[string]any{"name": artistName, "id": artistID},
|
||||||
},
|
},
|
||||||
"description": strings.TrimSpace(stringFromAny(info["description"])),
|
"description": strings.TrimSpace(jsonutil.StringFromAny(info["description"])),
|
||||||
"genre": strings.TrimSpace(stringFromAny(info["genre"])),
|
"genre": strings.TrimSpace(jsonutil.StringFromAny(info["genre"])),
|
||||||
"isrc": strings.TrimSpace(stringFromAny(info["isrc"])),
|
"isrc": strings.TrimSpace(jsonutil.StringFromAny(info["isrc"])),
|
||||||
"label": strings.TrimSpace(firstNonEmpty(stringFromAny(info["label"]), stringFromAny(info["label_name"]))),
|
"label": strings.TrimSpace(jsonutil.FirstNonEmpty(jsonutil.StringFromAny(info["label"]), jsonutil.StringFromAny(info["label_name"]))),
|
||||||
"copyright": strings.TrimSpace(stringFromAny(publisher["p_line"])),
|
"copyright": strings.TrimSpace(jsonutil.StringFromAny(publisher["p_line"])),
|
||||||
"release_date": strings.TrimSpace(firstNonEmpty(
|
"release_date": strings.TrimSpace(jsonutil.FirstNonEmpty(
|
||||||
stringFromAny(info["created_at"]),
|
jsonutil.StringFromAny(info["created_at"]),
|
||||||
stringFromAny(info["release_date"]),
|
jsonutil.StringFromAny(info["release_date"]),
|
||||||
stringFromAny(info["upload_date"]),
|
jsonutil.StringFromAny(info["upload_date"]),
|
||||||
)),
|
)),
|
||||||
}
|
}
|
||||||
if trackID := strings.TrimSpace(stringFromAny(info["id"])); trackID != "" {
|
if trackID := strings.TrimSpace(jsonutil.StringFromAny(info["id"])); trackID != "" {
|
||||||
meta["source_track_id"] = trackID
|
meta["source_track_id"] = trackID
|
||||||
}
|
}
|
||||||
|
|
||||||
if boolFromAny(publisher["explicit"]) || intFromAny(info["age_limit"]) >= 18 {
|
if jsonutil.BoolFromAny(publisher["explicit"]) || jsonutil.IntFromAny(info["age_limit"]) >= 18 {
|
||||||
meta["explicit"] = true
|
meta["explicit"] = true
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -405,11 +422,11 @@ func trackMetadataFromInfo(id string, info map[string]any) map[string]any {
|
|||||||
delete(meta, "release_date")
|
delete(meta, "release_date")
|
||||||
}
|
}
|
||||||
|
|
||||||
if thumb := strings.TrimSpace(stringFromAny(info["thumbnail"])); thumb != "" {
|
if thumb := strings.TrimSpace(jsonutil.StringFromAny(info["thumbnail"])); thumb != "" {
|
||||||
meta["image"] = soundcloudImageMap(thumb)
|
meta["image"] = soundcloudImageMap(thumb)
|
||||||
}
|
}
|
||||||
|
|
||||||
if strings.TrimSpace(stringFromAny(info["album"])) == "" && strings.TrimSpace(stringFromAny(publisher["album_title"])) == "" {
|
if strings.TrimSpace(jsonutil.StringFromAny(info["album"])) == "" && strings.TrimSpace(jsonutil.StringFromAny(publisher["album_title"])) == "" {
|
||||||
meta["album"] = map[string]any{
|
meta["album"] = map[string]any{
|
||||||
"id": canonicalID,
|
"id": canonicalID,
|
||||||
"title": title,
|
"title": title,
|
||||||
@@ -417,7 +434,7 @@ func trackMetadataFromInfo(id string, info map[string]any) map[string]any {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if durationSec := intFromAny(info["duration"]); durationSec > 0 {
|
if durationSec := jsonutil.IntFromAny(info["duration"]); durationSec > 0 {
|
||||||
meta["duration"] = durationSec
|
meta["duration"] = durationSec
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -426,7 +443,7 @@ func trackMetadataFromInfo(id string, info map[string]any) map[string]any {
|
|||||||
|
|
||||||
func canonicalSoundcloudURL(info map[string]any) string {
|
func canonicalSoundcloudURL(info map[string]any) string {
|
||||||
for _, key := range []string{"webpage_url", "original_url", "url"} {
|
for _, key := range []string{"webpage_url", "original_url", "url"} {
|
||||||
raw := strings.TrimSpace(stringFromAny(info[key]))
|
raw := strings.TrimSpace(jsonutil.StringFromAny(info[key]))
|
||||||
if raw == "" {
|
if raw == "" {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@@ -478,72 +495,6 @@ func asAnySlice(v any) []any {
|
|||||||
return items
|
return items
|
||||||
}
|
}
|
||||||
|
|
||||||
func stringFromAny(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 ""
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func intFromAny(v any) int {
|
|
||||||
switch t := v.(type) {
|
|
||||||
case int:
|
|
||||||
return t
|
|
||||||
case int64:
|
|
||||||
return int(t)
|
|
||||||
case float64:
|
|
||||||
return int(t)
|
|
||||||
case string:
|
|
||||||
i, _ := strconv.Atoi(strings.TrimSpace(t))
|
|
||||||
return i
|
|
||||||
default:
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func firstNonEmpty(items ...string) string {
|
|
||||||
for _, item := range items {
|
|
||||||
if strings.TrimSpace(item) != "" {
|
|
||||||
return strings.TrimSpace(item)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
func nestedMap(m map[string]any, key string) map[string]any {
|
|
||||||
v, ok := m[key].(map[string]any)
|
|
||||||
if !ok {
|
|
||||||
return map[string]any{}
|
|
||||||
}
|
|
||||||
return v
|
|
||||||
}
|
|
||||||
|
|
||||||
func boolFromAny(v any) bool {
|
|
||||||
switch t := v.(type) {
|
|
||||||
case bool:
|
|
||||||
return t
|
|
||||||
case string:
|
|
||||||
l := strings.ToLower(strings.TrimSpace(t))
|
|
||||||
return l == "1" || l == "true" || l == "yes"
|
|
||||||
case int:
|
|
||||||
return t != 0
|
|
||||||
case int64:
|
|
||||||
return t != 0
|
|
||||||
case float64:
|
|
||||||
return t != 0
|
|
||||||
default:
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func soundcloudImageMap(raw string) map[string]any {
|
func soundcloudImageMap(raw string) map[string]any {
|
||||||
base := strings.TrimSpace(raw)
|
base := strings.TrimSpace(raw)
|
||||||
if base == "" {
|
if base == "" {
|
||||||
|
|||||||
@@ -8,6 +8,8 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"streamrip-go/internal/jsonutil"
|
||||||
|
|
||||||
"streamrip-go/internal/config"
|
"streamrip-go/internal/config"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -27,11 +29,11 @@ func TestGetTrackMetadataAndDownloadable(t *testing.T) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("GetMetadata() error = %v", err)
|
t.Fatalf("GetMetadata() error = %v", err)
|
||||||
}
|
}
|
||||||
if stringFromAny(meta["title"]) != "Lean On" {
|
if jsonutil.StringFromAny(meta["title"]) != "Lean On" {
|
||||||
t.Fatalf("title = %q, want Lean On", stringFromAny(meta["title"]))
|
t.Fatalf("title = %q, want Lean On", jsonutil.StringFromAny(meta["title"]))
|
||||||
}
|
}
|
||||||
if stringFromAny(meta["id"]) != "https://soundcloud.com/a/b" {
|
if jsonutil.StringFromAny(meta["id"]) != "https://soundcloud.com/a/b" {
|
||||||
t.Fatalf("id = %q, want canonical soundcloud url", stringFromAny(meta["id"]))
|
t.Fatalf("id = %q, want canonical soundcloud url", jsonutil.StringFromAny(meta["id"]))
|
||||||
}
|
}
|
||||||
|
|
||||||
d, err := c.GetDownloadable(context.Background(), "https://soundcloud.com/a/b", 0)
|
d, err := c.GetDownloadable(context.Background(), "https://soundcloud.com/a/b", 0)
|
||||||
@@ -41,6 +43,9 @@ func TestGetTrackMetadataAndDownloadable(t *testing.T) {
|
|||||||
if d.URL != "https://cdn.example/audio.m4a" || d.Extension != "m4a" {
|
if d.URL != "https://cdn.example/audio.m4a" || d.Extension != "m4a" {
|
||||||
t.Fatalf("unexpected downloadable: %+v", d)
|
t.Fatalf("unexpected downloadable: %+v", d)
|
||||||
}
|
}
|
||||||
|
if d.Audio.Container != "M4A" || d.Audio.Codec != "AAC" {
|
||||||
|
t.Fatalf("unexpected audio profile: %+v", d.Audio)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestGetPlaylistMetadata(t *testing.T) {
|
func TestGetPlaylistMetadata(t *testing.T) {
|
||||||
@@ -59,8 +64,8 @@ func TestGetPlaylistMetadata(t *testing.T) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("GetMetadata() error = %v", err)
|
t.Fatalf("GetMetadata() error = %v", err)
|
||||||
}
|
}
|
||||||
if stringFromAny(meta["name"]) != "Road Trip" {
|
if jsonutil.StringFromAny(meta["name"]) != "Road Trip" {
|
||||||
t.Fatalf("name = %q, want Road Trip", stringFromAny(meta["name"]))
|
t.Fatalf("name = %q, want Road Trip", jsonutil.StringFromAny(meta["name"]))
|
||||||
}
|
}
|
||||||
tracksMap, ok := meta["tracks"].(map[string]any)
|
tracksMap, ok := meta["tracks"].(map[string]any)
|
||||||
if !ok {
|
if !ok {
|
||||||
@@ -70,8 +75,8 @@ func TestGetPlaylistMetadata(t *testing.T) {
|
|||||||
if len(items) != 2 {
|
if len(items) != 2 {
|
||||||
t.Fatalf("playlist items len = %d, want 2", len(items))
|
t.Fatalf("playlist items len = %d, want 2", len(items))
|
||||||
}
|
}
|
||||||
if stringFromAny(meta["id"]) != "https://soundcloud.com/a/sets/road-trip" {
|
if jsonutil.StringFromAny(meta["id"]) != "https://soundcloud.com/a/sets/road-trip" {
|
||||||
t.Fatalf("playlist id not canonical: %q", stringFromAny(meta["id"]))
|
t.Fatalf("playlist id not canonical: %q", jsonutil.StringFromAny(meta["id"]))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -102,8 +107,8 @@ func TestSearchTrack(t *testing.T) {
|
|||||||
if !ok {
|
if !ok {
|
||||||
t.Fatalf("expected first item map")
|
t.Fatalf("expected first item map")
|
||||||
}
|
}
|
||||||
if stringFromAny(item0["id"]) != "https://soundcloud.com/a/b" {
|
if jsonutil.StringFromAny(item0["id"]) != "https://soundcloud.com/a/b" {
|
||||||
t.Fatalf("track search id not canonical: %q", stringFromAny(item0["id"]))
|
t.Fatalf("track search id not canonical: %q", jsonutil.StringFromAny(item0["id"]))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -147,8 +152,8 @@ func TestSearchPlaylist(t *testing.T) {
|
|||||||
if !ok {
|
if !ok {
|
||||||
t.Fatalf("expected first item map")
|
t.Fatalf("expected first item map")
|
||||||
}
|
}
|
||||||
if stringFromAny(item0["id"]) != "https://soundcloud.com/a/sets/road-trip" {
|
if jsonutil.StringFromAny(item0["id"]) != "https://soundcloud.com/a/sets/road-trip" {
|
||||||
t.Fatalf("playlist search id not canonical: %q", stringFromAny(item0["id"]))
|
t.Fatalf("playlist search id not canonical: %q", jsonutil.StringFromAny(item0["id"]))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -192,8 +197,8 @@ func TestSearchPlaylistAcceptsDotsInPath(t *testing.T) {
|
|||||||
if !ok {
|
if !ok {
|
||||||
t.Fatalf("expected first item map")
|
t.Fatalf("expected first item map")
|
||||||
}
|
}
|
||||||
if stringFromAny(item0["id"]) != "https://soundcloud.com/artist.name/sets/road.trip" {
|
if jsonutil.StringFromAny(item0["id"]) != "https://soundcloud.com/artist.name/sets/road.trip" {
|
||||||
t.Fatalf("playlist search id not canonical: %q", stringFromAny(item0["id"]))
|
t.Fatalf("playlist search id not canonical: %q", jsonutil.StringFromAny(item0["id"]))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -221,18 +226,18 @@ func TestTrackMetadataIncludesExplicitAndISRC(t *testing.T) {
|
|||||||
"thumbnail": "https://img",
|
"thumbnail": "https://img",
|
||||||
"upload_date": "20240101",
|
"upload_date": "20240101",
|
||||||
})
|
})
|
||||||
if stringFromAny(meta["isrc"]) != "US123" {
|
if jsonutil.StringFromAny(meta["isrc"]) != "US123" {
|
||||||
t.Fatalf("isrc = %q, want US123", stringFromAny(meta["isrc"]))
|
t.Fatalf("isrc = %q, want US123", jsonutil.StringFromAny(meta["isrc"]))
|
||||||
}
|
}
|
||||||
explicit, _ := meta["explicit"].(bool)
|
explicit, _ := meta["explicit"].(bool)
|
||||||
if !explicit {
|
if !explicit {
|
||||||
t.Fatalf("expected explicit=true")
|
t.Fatalf("expected explicit=true")
|
||||||
}
|
}
|
||||||
if stringFromAny(meta["source_track_id"]) != "9876" {
|
if jsonutil.StringFromAny(meta["source_track_id"]) != "9876" {
|
||||||
t.Fatalf("source_track_id = %q, want 9876", stringFromAny(meta["source_track_id"]))
|
t.Fatalf("source_track_id = %q, want 9876", jsonutil.StringFromAny(meta["source_track_id"]))
|
||||||
}
|
}
|
||||||
if stringFromAny(nestedMap(meta, "album")["title"]) != "T" {
|
if jsonutil.StringFromAny(jsonutil.NestedMap(meta, "album")["title"]) != "T" {
|
||||||
t.Fatalf("album title mismatch: %#v", nestedMap(meta, "album"))
|
t.Fatalf("album title mismatch: %#v", jsonutil.NestedMap(meta, "album"))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"streamrip-go/internal/config"
|
"streamrip-go/internal/config"
|
||||||
|
"streamrip-go/internal/jsonutil"
|
||||||
"streamrip-go/internal/netutil"
|
"streamrip-go/internal/netutil"
|
||||||
"streamrip-go/internal/provider"
|
"streamrip-go/internal/provider"
|
||||||
"streamrip-go/internal/ratelimit"
|
"streamrip-go/internal/ratelimit"
|
||||||
@@ -22,6 +23,7 @@ import (
|
|||||||
|
|
||||||
const (
|
const (
|
||||||
baseURL = "https://api.tidalhifi.com/v1"
|
baseURL = "https://api.tidalhifi.com/v1"
|
||||||
|
lyricsAPIv1 = "https://api.tidal.com/v1"
|
||||||
openAPIV2 = "https://openapi.tidal.com/v2"
|
openAPIV2 = "https://openapi.tidal.com/v2"
|
||||||
authURL = "https://auth.tidal.com/v1/oauth2"
|
authURL = "https://auth.tidal.com/v1/oauth2"
|
||||||
clientID = "fX2JxdmntZWK0ixT"
|
clientID = "fX2JxdmntZWK0ixT"
|
||||||
@@ -36,12 +38,12 @@ var qualityMap = map[int]string{
|
|||||||
4: "HI_RES_LOSSLESS",
|
4: "HI_RES_LOSSLESS",
|
||||||
}
|
}
|
||||||
|
|
||||||
var qualityToFormat = map[int]string{
|
var qualityToFormats = map[int][]string{
|
||||||
0: "HEAACV1",
|
0: {"HEAACV1"},
|
||||||
1: "AACLC",
|
1: {"HEAACV1", "AACLC"},
|
||||||
2: "FLAC",
|
2: {"HEAACV1", "AACLC", "FLAC"},
|
||||||
3: "FLAC_HIRES",
|
3: {"HEAACV1", "AACLC", "FLAC", "FLAC_HIRES"},
|
||||||
4: "FLAC_HIRES",
|
4: {"HEAACV1", "AACLC", "FLAC", "FLAC_HIRES"},
|
||||||
}
|
}
|
||||||
|
|
||||||
var atmosAudioQualities = []string{"HI_RES_LOSSLESS", "HI_RES", "LOSSLESS", "HIGH"}
|
var atmosAudioQualities = []string{"HI_RES_LOSSLESS", "HI_RES", "LOSSLESS", "HIGH"}
|
||||||
@@ -53,15 +55,19 @@ type Client struct {
|
|||||||
http *http.Client
|
http *http.Client
|
||||||
limiter *ratelimit.Limiter
|
limiter *ratelimit.Limiter
|
||||||
baseURL string
|
baseURL string
|
||||||
|
lyricsAPI string
|
||||||
|
openAPI string
|
||||||
loggedIn bool
|
loggedIn bool
|
||||||
}
|
}
|
||||||
|
|
||||||
func New(cfg *config.Config) *Client {
|
func New(cfg *config.Config) *Client {
|
||||||
return &Client{
|
return &Client{
|
||||||
cfg: cfg,
|
cfg: cfg,
|
||||||
http: netutil.NewHTTPClient(30*time.Second, cfg.Session.Downloads.VerifySSL),
|
http: netutil.NewHTTPClient(30*time.Second, cfg.Session.Downloads.VerifySSL, cfg.Session.Downloads.MaxConnections),
|
||||||
limiter: ratelimit.New(cfg.Session.Downloads.RequestsPerMinute),
|
limiter: ratelimit.New(cfg.Session.Downloads.RequestsPerMinute),
|
||||||
baseURL: baseURL,
|
baseURL: baseURL,
|
||||||
|
lyricsAPI: lyricsAPIv1,
|
||||||
|
openAPI: openAPIV2,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -149,7 +155,7 @@ func (c *Client) refreshAccessToken(ctx context.Context) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
newRefresh := stringify(resp["refresh_token"])
|
newRefresh := stringify(resp["refresh_token"])
|
||||||
expiresIn := int64(intFromAny(resp["expires_in"]))
|
expiresIn := int64(jsonutil.IntFromAny(resp["expires_in"]))
|
||||||
if expiresIn <= 0 {
|
if expiresIn <= 0 {
|
||||||
expiresIn = 7 * 24 * 3600
|
expiresIn = 7 * 24 * 3600
|
||||||
}
|
}
|
||||||
@@ -203,11 +209,52 @@ func (c *Client) GetMetadata(ctx context.Context, item, mediaType string) (map[s
|
|||||||
if album, ok := resp["album"].(map[string]any); ok {
|
if album, ok := resp["album"].(map[string]any); ok {
|
||||||
enrichTidalImage(album)
|
enrichTidalImage(album)
|
||||||
}
|
}
|
||||||
|
// Lyrics live on a separate endpoint, so fetching them costs an extra
|
||||||
|
// rate-limited roundtrip per track. Users who don't embed lyrics can
|
||||||
|
// opt out via metadata.exclude = ["lyrics"].
|
||||||
|
if !c.lyricsExcluded() {
|
||||||
|
if lyrics, lrc := c.fetchTrackLyrics(ctx, item); lyrics != "" || lrc != "" {
|
||||||
|
if lyrics != "" {
|
||||||
|
resp["lyrics"] = lyrics
|
||||||
|
}
|
||||||
|
if lrc != "" {
|
||||||
|
resp["lyrics_synced"] = lrc
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return resp, nil
|
return resp, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (c *Client) lyricsExcluded() bool {
|
||||||
|
for _, k := range c.cfg.Session.Metadata.Exclude {
|
||||||
|
if strings.EqualFold(strings.TrimSpace(k), "lyrics") {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) fetchTrackLyrics(ctx context.Context, trackID string) (string, string) {
|
||||||
|
params := url.Values{}
|
||||||
|
params.Set("deviceType", "PHONE")
|
||||||
|
params.Set("locale", "en_US")
|
||||||
|
params.Set("platform", "ANDROID")
|
||||||
|
|
||||||
|
resp, status, err := c.apiRequest(ctx, "tracks/"+url.PathEscape(strings.TrimSpace(trackID))+"/lyrics", params, c.lyricsAPI)
|
||||||
|
if err != nil {
|
||||||
|
return "", ""
|
||||||
|
}
|
||||||
|
if status != http.StatusOK {
|
||||||
|
return "", ""
|
||||||
|
}
|
||||||
|
|
||||||
|
lyrics := strings.TrimSpace(stringify(resp["lyrics"]))
|
||||||
|
lrc := strings.TrimSpace(stringify(resp["subtitles"]))
|
||||||
|
return lyrics, lrc
|
||||||
|
}
|
||||||
|
|
||||||
func (c *Client) Search(ctx context.Context, mediaType, query string, limit int) ([]map[string]any, error) {
|
func (c *Client) Search(ctx context.Context, mediaType, query string, limit int) ([]map[string]any, error) {
|
||||||
if !c.loggedIn {
|
if !c.loggedIn {
|
||||||
return nil, errors.New("tidal client not logged in")
|
return nil, errors.New("tidal client not logged in")
|
||||||
@@ -244,12 +291,13 @@ func (c *Client) GetDownloadable(ctx context.Context, trackID string, quality in
|
|||||||
}
|
}
|
||||||
|
|
||||||
if c.cfg.Session.Tidal.PreferAtmos {
|
if c.cfg.Session.Tidal.PreferAtmos {
|
||||||
if c.trackSupportsAtmos(ctx, trackID) {
|
// No tracks/{id} pre-check: getAtmosDownloadable already validates
|
||||||
|
// each candidate response via playbackLooksAtmos and falls back
|
||||||
|
// through the format-specific trackManifests paths.
|
||||||
if d, _ := c.getAtmosDownloadable(ctx, trackID); d != nil {
|
if d, _ := c.getAtmosDownloadable(ctx, trackID); d != nil {
|
||||||
return d, nil
|
return d, nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
params := url.Values{}
|
params := url.Values{}
|
||||||
params.Set("audioquality", qualityMap[quality])
|
params.Set("audioquality", qualityMap[quality])
|
||||||
@@ -262,6 +310,15 @@ func (c *Client) GetDownloadable(ctx context.Context, trackID string, quality in
|
|||||||
}
|
}
|
||||||
if status == http.StatusOK {
|
if status == http.StatusOK {
|
||||||
if d := downloadableFromPlaybackManifest(resp); d != nil {
|
if d := downloadableFromPlaybackManifest(resp); d != nil {
|
||||||
|
// Tidal's playbackinfo sometimes returns an m4a (HIGH/AAC)
|
||||||
|
// stream even when LOSSLESS+ was requested. There is no
|
||||||
|
// lossless m4a tier, so retry via the openAPI v2 manifest
|
||||||
|
// before settling for the downgrade.
|
||||||
|
if quality >= 2 && d.Extension == "m4a" {
|
||||||
|
if strict, strictErr := c.getDownloadableFromTrackManifest(ctx, trackID, quality); strictErr == nil && strict != nil {
|
||||||
|
return strict, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
return d, nil
|
return d, nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -474,19 +531,23 @@ func (c *Client) fetchArtistAlbums(ctx context.Context, artistID string) ([]map[
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (c *Client) getDownloadableFromTrackManifest(ctx context.Context, trackID string, quality int) (*provider.Downloadable, error) {
|
func (c *Client) getDownloadableFromTrackManifest(ctx context.Context, trackID string, quality int) (*provider.Downloadable, error) {
|
||||||
format := qualityToFormat[quality]
|
formats := formatsForQuality(quality, c.cfg.Session.Tidal.PreferAtmos)
|
||||||
return c.getDownloadableFromTrackManifestForFormat(ctx, trackID, format)
|
return c.getDownloadableFromTrackManifestForFormats(ctx, trackID, formats)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Client) getDownloadableFromTrackManifestForFormat(ctx context.Context, trackID, format string) (*provider.Downloadable, error) {
|
func (c *Client) getDownloadableFromTrackManifestForFormat(ctx context.Context, trackID, format string) (*provider.Downloadable, error) {
|
||||||
|
return c.getDownloadableFromTrackManifestForFormats(ctx, trackID, []string{format})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) getDownloadableFromTrackManifestForFormats(ctx context.Context, trackID string, formats []string) (*provider.Downloadable, error) {
|
||||||
params := url.Values{}
|
params := url.Values{}
|
||||||
params.Set("manifestType", "MPEG_DASH")
|
params.Set("manifestType", "MPEG_DASH")
|
||||||
params.Set("formats", format)
|
params.Set("formats", strings.Join(formats, ","))
|
||||||
params.Set("uriScheme", "HTTPS")
|
params.Set("uriScheme", "HTTPS")
|
||||||
params.Set("usage", "PLAYBACK")
|
params.Set("usage", "PLAYBACK")
|
||||||
params.Set("adaptive", "false")
|
params.Set("adaptive", "false")
|
||||||
|
|
||||||
resp, status, err := c.apiRequest(ctx, "trackManifests/"+trackID, params, openAPIV2)
|
resp, status, err := c.apiRequest(ctx, "trackManifests/"+trackID, params, c.openAPI)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -506,9 +567,9 @@ func (c *Client) getDownloadableFromTrackManifestForFormat(ctx context.Context,
|
|||||||
if uri == "" {
|
if uri == "" {
|
||||||
return nil, errors.New("tidal trackManifests missing uri")
|
return nil, errors.New("tidal trackManifests missing uri")
|
||||||
}
|
}
|
||||||
formats, _ := attrs["formats"].([]any)
|
attrFormats, _ := attrs["formats"].([]any)
|
||||||
ext := "m4a"
|
ext := "m4a"
|
||||||
for _, f := range formats {
|
for _, f := range attrFormats {
|
||||||
fv := strings.ToUpper(stringify(f))
|
fv := strings.ToUpper(stringify(f))
|
||||||
if strings.Contains(fv, "FLAC") {
|
if strings.Contains(fv, "FLAC") {
|
||||||
ext = "flac"
|
ext = "flac"
|
||||||
@@ -519,7 +580,23 @@ func (c *Client) getDownloadableFromTrackManifestForFormat(ctx context.Context,
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return &provider.Downloadable{URL: uri, Extension: ext, Source: "tidal"}, nil
|
profile := tidalAudioProfileFromFormats(attrFormats)
|
||||||
|
if profile.Container == "" {
|
||||||
|
profile = tidalAudioProfileFromExtension(ext)
|
||||||
|
}
|
||||||
|
return &provider.Downloadable{URL: uri, Extension: ext, Source: "tidal", Audio: profile}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func formatsForQuality(quality int, preferAtmos bool) []string {
|
||||||
|
base, ok := qualityToFormats[quality]
|
||||||
|
if !ok {
|
||||||
|
base = qualityToFormats[0]
|
||||||
|
}
|
||||||
|
out := append([]string(nil), base...)
|
||||||
|
if preferAtmos {
|
||||||
|
out = append(out, "EAC3_JOC")
|
||||||
|
}
|
||||||
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Client) GetVideoDownloadable(ctx context.Context, videoID string) (*provider.Downloadable, error) {
|
func (c *Client) GetVideoDownloadable(ctx context.Context, videoID string) (*provider.Downloadable, error) {
|
||||||
@@ -614,7 +691,121 @@ func downloadableFromPlaybackManifest(resp map[string]any) *provider.Downloadabl
|
|||||||
} else if strings.Contains(codec, "ec-3") || strings.Contains(codec, "eac3") || strings.Contains(codec, "joc") || strings.Contains(codec, "atmos") {
|
} else if strings.Contains(codec, "ec-3") || strings.Contains(codec, "eac3") || strings.Contains(codec, "joc") || strings.Contains(codec, "atmos") {
|
||||||
ext = "mka"
|
ext = "mka"
|
||||||
}
|
}
|
||||||
return &provider.Downloadable{URL: streamURL, Extension: ext, Source: "tidal"}
|
profile := tidalAudioProfileFromCodec(codec)
|
||||||
|
if profile.Container == "" {
|
||||||
|
profile = tidalAudioProfileFromExtension(ext)
|
||||||
|
}
|
||||||
|
audioQuality := strings.ToUpper(strings.TrimSpace(stringify(resp["audioQuality"])))
|
||||||
|
if audioQuality == "" {
|
||||||
|
audioQuality = strings.ToUpper(strings.TrimSpace(stringify(manifest["audioQuality"])))
|
||||||
|
}
|
||||||
|
if audioQuality != "" {
|
||||||
|
profile = applyTidalAudioQuality(profile, audioQuality)
|
||||||
|
}
|
||||||
|
if strings.Contains(strings.ToUpper(stringify(resp["audioMode"])), "ATMOS") {
|
||||||
|
profile = tidalAtmosAudioProfile()
|
||||||
|
}
|
||||||
|
return &provider.Downloadable{URL: streamURL, Extension: ext, Source: "tidal", Audio: profile}
|
||||||
|
}
|
||||||
|
|
||||||
|
func tidalAudioProfileFromFormats(formats []any) provider.AudioProfile {
|
||||||
|
best := provider.AudioProfile{}
|
||||||
|
for _, raw := range formats {
|
||||||
|
f := strings.ToUpper(strings.TrimSpace(stringify(raw)))
|
||||||
|
switch {
|
||||||
|
case strings.Contains(f, "EAC3") || strings.Contains(f, "JOC") || strings.Contains(f, "ATMOS"):
|
||||||
|
return tidalAtmosAudioProfile()
|
||||||
|
case strings.Contains(f, "FLAC_HIRES"):
|
||||||
|
best = provider.AudioProfile{Container: "FLAC", Codec: "FLAC", Quality: "HI_RES_LOSSLESS", BitDepth: 24}
|
||||||
|
case strings.Contains(f, "FLAC"):
|
||||||
|
if best.Container == "" {
|
||||||
|
best = provider.AudioProfile{Container: "FLAC", Codec: "FLAC", Quality: "LOSSLESS", BitDepth: 16, SamplingRate: "44.1"}
|
||||||
|
}
|
||||||
|
case strings.Contains(f, "AACLC"):
|
||||||
|
if best.Container == "" {
|
||||||
|
best = provider.AudioProfile{Container: "M4A", Codec: "AACLC", Quality: "HIGH", BitDepth: 16, SamplingRate: "44.1", BitrateKbps: 320}
|
||||||
|
}
|
||||||
|
case strings.Contains(f, "HEAAC"):
|
||||||
|
if best.Container == "" {
|
||||||
|
best = provider.AudioProfile{Container: "M4A", Codec: "HEAACV1", Quality: "LOW", BitDepth: 16, SamplingRate: "44.1", BitrateKbps: 96}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return best
|
||||||
|
}
|
||||||
|
|
||||||
|
func tidalAudioProfileFromCodec(codec string) provider.AudioProfile {
|
||||||
|
c := strings.ToLower(strings.TrimSpace(codec))
|
||||||
|
switch {
|
||||||
|
case strings.Contains(c, "ec-3") || strings.Contains(c, "eac3") || strings.Contains(c, "joc") || strings.Contains(c, "atmos"):
|
||||||
|
return tidalAtmosAudioProfile()
|
||||||
|
case strings.Contains(c, "flac"):
|
||||||
|
return provider.AudioProfile{Container: "FLAC", Codec: "FLAC", Quality: "LOSSLESS", BitDepth: 16, SamplingRate: "44.1"}
|
||||||
|
case strings.Contains(c, "mp4a.40.5") || strings.Contains(c, "mp4a.40.29"):
|
||||||
|
return provider.AudioProfile{Container: "M4A", Codec: "HEAACV1", Quality: "LOW", BitDepth: 16, SamplingRate: "44.1", BitrateKbps: 96}
|
||||||
|
case strings.Contains(c, "mp4a") || strings.Contains(c, "aac"):
|
||||||
|
return provider.AudioProfile{Container: "M4A", Codec: "AACLC", Quality: "HIGH", BitDepth: 16, SamplingRate: "44.1", BitrateKbps: 320}
|
||||||
|
default:
|
||||||
|
return provider.AudioProfile{}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func tidalAtmosAudioProfile() provider.AudioProfile {
|
||||||
|
return provider.AudioProfile{Container: "MKA", Codec: "EAC3_JOC", Quality: "ATMOS", BitDepth: 32, SamplingRate: "48"}
|
||||||
|
}
|
||||||
|
|
||||||
|
func tidalAudioProfileFromExtension(ext string) provider.AudioProfile {
|
||||||
|
switch strings.ToLower(strings.TrimSpace(ext)) {
|
||||||
|
case "flac":
|
||||||
|
return provider.AudioProfile{Container: "FLAC", Codec: "FLAC", Quality: "LOSSLESS", BitDepth: 16, SamplingRate: "44.1"}
|
||||||
|
case "mka":
|
||||||
|
return tidalAtmosAudioProfile()
|
||||||
|
case "m4a":
|
||||||
|
return provider.AudioProfile{Container: "M4A", Codec: "AACLC", Quality: "HIGH", BitDepth: 16, SamplingRate: "44.1", BitrateKbps: 320}
|
||||||
|
default:
|
||||||
|
container := strings.ToUpper(strings.TrimSpace(ext))
|
||||||
|
if container == "" {
|
||||||
|
container = "M4A"
|
||||||
|
}
|
||||||
|
return provider.AudioProfile{Container: container, Codec: container}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func applyTidalAudioQuality(profile provider.AudioProfile, audioQuality string) provider.AudioProfile {
|
||||||
|
aq := strings.ToUpper(strings.TrimSpace(audioQuality))
|
||||||
|
if aq == "" {
|
||||||
|
return profile
|
||||||
|
}
|
||||||
|
profile.Quality = aq
|
||||||
|
switch aq {
|
||||||
|
case "HI_RES", "HI_RES_LOSSLESS":
|
||||||
|
if strings.EqualFold(profile.Container, "FLAC") {
|
||||||
|
if profile.BitDepth < 24 {
|
||||||
|
profile.BitDepth = 24
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case "LOSSLESS":
|
||||||
|
if strings.EqualFold(profile.Container, "FLAC") {
|
||||||
|
if profile.BitDepth == 0 {
|
||||||
|
profile.BitDepth = 16
|
||||||
|
}
|
||||||
|
if profile.SamplingRate == "" {
|
||||||
|
profile.SamplingRate = "44.1"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case "HIGH":
|
||||||
|
if strings.EqualFold(profile.Container, "M4A") && profile.BitrateKbps == 0 {
|
||||||
|
profile.BitrateKbps = 320
|
||||||
|
}
|
||||||
|
case "LOW":
|
||||||
|
if strings.EqualFold(profile.Container, "M4A") {
|
||||||
|
profile.Codec = "HEAACV1"
|
||||||
|
if profile.BitrateKbps == 0 {
|
||||||
|
profile.BitrateKbps = 96
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return profile
|
||||||
}
|
}
|
||||||
|
|
||||||
func bestHLSVariantURL(masterURL, playlist string) string {
|
func bestHLSVariantURL(masterURL, playlist string) string {
|
||||||
@@ -773,19 +964,3 @@ func tidalImageMap(cover string) map[string]any {
|
|||||||
"original": base + "/1280x1280.jpg",
|
"original": base + "/1280x1280.jpg",
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func intFromAny(v any) int {
|
|
||||||
switch t := v.(type) {
|
|
||||||
case int:
|
|
||||||
return t
|
|
||||||
case int64:
|
|
||||||
return int(t)
|
|
||||||
case float64:
|
|
||||||
return int(t)
|
|
||||||
case string:
|
|
||||||
i, _ := strconv.Atoi(t)
|
|
||||||
return i
|
|
||||||
default:
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
|
"reflect"
|
||||||
"strconv"
|
"strconv"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
@@ -161,6 +162,82 @@ func TestGetMetadataArtistPaginatesAlbums(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestGetMetadataTrackAddsLyricsAndSyncedLyrics(t *testing.T) {
|
||||||
|
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
switch r.URL.Path {
|
||||||
|
case "/v1/tracks/42":
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]any{"id": 42, "title": "Song", "album": map[string]any{"id": 10, "title": "Album"}})
|
||||||
|
case "/v1/tracks/42/lyrics":
|
||||||
|
q := r.URL.Query()
|
||||||
|
if q.Get("deviceType") != "PHONE" || q.Get("locale") != "en_US" || q.Get("platform") != "ANDROID" || q.Get("countryCode") != "MY" {
|
||||||
|
w.WriteHeader(http.StatusBadRequest)
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]any{"error": "bad query"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||||
|
"lyrics": "plain lyrics line",
|
||||||
|
"subtitles": "[00:00.00]plain lyrics line",
|
||||||
|
})
|
||||||
|
default:
|
||||||
|
w.WriteHeader(http.StatusNotFound)
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
defer ts.Close()
|
||||||
|
|
||||||
|
cfgData := config.DefaultConfigData()
|
||||||
|
cfgData.Tidal.AccessToken = "token"
|
||||||
|
cfgData.Tidal.CountryCode = "MY"
|
||||||
|
c := New(&config.Config{File: cfgData, Session: cfgData})
|
||||||
|
c.loggedIn = true
|
||||||
|
c.baseURL = ts.URL + "/v1"
|
||||||
|
c.lyricsAPI = ts.URL + "/v1"
|
||||||
|
|
||||||
|
meta, err := c.GetMetadata(context.Background(), "42", "track")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("GetMetadata() err = %v", err)
|
||||||
|
}
|
||||||
|
if got := stringify(meta["lyrics"]); got != "plain lyrics line" {
|
||||||
|
t.Fatalf("lyrics = %q, want plain lyrics line", got)
|
||||||
|
}
|
||||||
|
if got := stringify(meta["lyrics_synced"]); got != "[00:00.00]plain lyrics line" {
|
||||||
|
t.Fatalf("lyrics_synced = %q, want synced lrc", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGetMetadataTrackIgnoresLyricsEndpointFailure(t *testing.T) {
|
||||||
|
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
switch r.URL.Path {
|
||||||
|
case "/v1/tracks/42":
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]any{"id": 42, "title": "Song"})
|
||||||
|
case "/v1/tracks/42/lyrics":
|
||||||
|
w.WriteHeader(http.StatusNotFound)
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]any{"error": "not found"})
|
||||||
|
default:
|
||||||
|
w.WriteHeader(http.StatusNotFound)
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
defer ts.Close()
|
||||||
|
|
||||||
|
cfgData := config.DefaultConfigData()
|
||||||
|
cfgData.Tidal.AccessToken = "token"
|
||||||
|
cfgData.Tidal.CountryCode = "US"
|
||||||
|
c := New(&config.Config{File: cfgData, Session: cfgData})
|
||||||
|
c.loggedIn = true
|
||||||
|
c.baseURL = ts.URL + "/v1"
|
||||||
|
c.lyricsAPI = ts.URL + "/v1"
|
||||||
|
|
||||||
|
meta, err := c.GetMetadata(context.Background(), "42", "track")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("GetMetadata() err = %v", err)
|
||||||
|
}
|
||||||
|
if _, ok := meta["lyrics"]; ok {
|
||||||
|
t.Fatalf("did not expect lyrics when endpoint fails")
|
||||||
|
}
|
||||||
|
if _, ok := meta["lyrics_synced"]; ok {
|
||||||
|
t.Fatalf("did not expect lyrics_synced when endpoint fails")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestGetDownloadablePrefersAtmosWhenEnabled(t *testing.T) {
|
func TestGetDownloadablePrefersAtmosWhenEnabled(t *testing.T) {
|
||||||
var calls []string
|
var calls []string
|
||||||
allImmersive := true
|
allImmersive := true
|
||||||
@@ -243,3 +320,78 @@ func TestTrackSupportsAtmosFromTags(t *testing.T) {
|
|||||||
t.Fatalf("expected atmos support from mediaMetadata tags")
|
t.Fatalf("expected atmos support from mediaMetadata tags")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestFormatsForQuality(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
q int
|
||||||
|
atmos bool
|
||||||
|
wants []string
|
||||||
|
}{
|
||||||
|
{name: "low", q: 0, wants: []string{"HEAACV1"}},
|
||||||
|
{name: "high", q: 1, wants: []string{"HEAACV1", "AACLC"}},
|
||||||
|
{name: "lossless", q: 2, wants: []string{"HEAACV1", "AACLC", "FLAC"}},
|
||||||
|
{name: "hires", q: 4, wants: []string{"HEAACV1", "AACLC", "FLAC", "FLAC_HIRES"}},
|
||||||
|
{name: "atmos adds eac3", q: 2, atmos: true, wants: []string{"HEAACV1", "AACLC", "FLAC", "EAC3_JOC"}},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tc := range tests {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
got := formatsForQuality(tc.q, tc.atmos)
|
||||||
|
if !reflect.DeepEqual(got, tc.wants) {
|
||||||
|
t.Fatalf("formatsForQuality(%d, atmos=%v) = %#v, want %#v", tc.q, tc.atmos, got, tc.wants)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGetDownloadableLosslessUsesTrackManifestWhenPlaybackIsAAC(t *testing.T) {
|
||||||
|
var gotFormats string
|
||||||
|
var ts *httptest.Server
|
||||||
|
ts = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
switch r.URL.Path {
|
||||||
|
case "/v1/tracks/42/playbackinfopostpaywall":
|
||||||
|
manifest := map[string]any{"urls": []string{ts.URL + "/aac.m3u8"}, "codecs": "mp4a.40.2"}
|
||||||
|
b, _ := json.Marshal(manifest)
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]any{"manifest": base64.StdEncoding.EncodeToString(b)})
|
||||||
|
case "/v2/trackManifests/42":
|
||||||
|
gotFormats = r.URL.Query().Get("formats")
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||||
|
"data": map[string]any{
|
||||||
|
"attributes": map[string]any{
|
||||||
|
"uri": ts.URL + "/song.flac",
|
||||||
|
"formats": []any{"FLAC"},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
default:
|
||||||
|
w.WriteHeader(http.StatusNotFound)
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
defer ts.Close()
|
||||||
|
|
||||||
|
cfgData := config.DefaultConfigData()
|
||||||
|
cfgData.Tidal.AccessToken = "token"
|
||||||
|
cfgData.Tidal.CountryCode = "US"
|
||||||
|
c := New(&config.Config{File: cfgData, Session: cfgData})
|
||||||
|
c.loggedIn = true
|
||||||
|
c.baseURL = ts.URL + "/v1"
|
||||||
|
c.openAPI = ts.URL + "/v2"
|
||||||
|
|
||||||
|
d, err := c.GetDownloadable(context.Background(), "42", 2)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("GetDownloadable() err = %v", err)
|
||||||
|
}
|
||||||
|
if gotFormats != "HEAACV1,AACLC,FLAC" {
|
||||||
|
t.Fatalf("formats query = %q, want %q", gotFormats, "HEAACV1,AACLC,FLAC")
|
||||||
|
}
|
||||||
|
if d.URL != ts.URL+"/song.flac" {
|
||||||
|
t.Fatalf("url = %q, want %q", d.URL, ts.URL+"/song.flac")
|
||||||
|
}
|
||||||
|
if d.Extension != "flac" {
|
||||||
|
t.Fatalf("extension = %q, want flac", d.Extension)
|
||||||
|
}
|
||||||
|
if d.Audio.Container != "FLAC" || d.Audio.Quality != "LOSSLESS" {
|
||||||
|
t.Fatalf("unexpected audio profile: %+v", d.Audio)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user