fix: audit fixes for credentials, auth races, and silent data loss

- redact credentials from transport errors, verbose request logs, and
  download-start logs; add sid/api_key/sign to sensitive params
- stop forwarding Yandex OAuth headers to API-supplied download hosts and
  give the last.fm mirror an opt-out and a notice
- serialize deezer token state, beatport token snapshots, and qobuz mobile
  KEK access so concurrent workers cannot race login refreshes
- suffix colliding track/video output names instead of overwriting
- propagate deezer/qobuz pagination errors, keep paginating when counts
  are missing, and return a non-zero exit for partial album/playlist rips
- clear failed_downloads rows on success and downloads rows on failure;
  open browse databases read-only; honor independent DB feature flags
- drop the redundant deezer metadata call, paginate Yandex searches,
  bound and rate-limit yt-dlp, and deep-clone the SoundCloud cache
- validate conversion codecs before ripping and isolate the qobuz convert
  smoke test from the real library
- write the config atomically and fix deezer slug-vs-id URL parsing
This commit is contained in:
Joren committed 2026-11-23 10:32:17 +01:00
1 parent 21406ea7c1
commit 1b13dace0e
22 files changed
+705 -226

No files matched your search

+3 -4
View File
@@ -106,10 +106,9 @@ func cmdDatabase(_ context.Context, cfg *config.Config, _ globalOptions, args []
fmt.Printf("%02d %s\n", i, id)
}
case "failed":
rows, listErr := listFailedRows(cfg.Session.Database.FailedDownloadsPath)
if listErr != nil && isNoSuchTableErr(listErr) && cfg.Session.Database.FailedDownloadsPath != cfg.Session.Database.DownloadsPath {
rows, listErr = listFailedRows(cfg.Session.Database.DownloadsPath)
}
// Failures are recorded in the main downloads database; the legacy
// failed_downloads_path setting is not written to by this program.
rows, listErr := listFailedRows(cfg.Session.Database.DownloadsPath)
if listErr != nil {
fmt.Fprintf(os.Stderr, "database browse error: %v\n", listErr)
return 1
+19
View File
@@ -44,6 +44,10 @@ func cmdURL(ctx context.Context, cfg *config.Config, gopts globalOptions, args [
}
if added == 0 {
if len(rawArgs) > 0 {
fmt.Fprintln(os.Stderr, "no valid urls queued")
return 1
}
fmt.Println("nothing to rip")
return 0
}
@@ -99,8 +103,10 @@ func cmdFile(ctx context.Context, cfg *config.Config, gopts globalOptions, args
mainApp.IgnoreDB = ignoreDB || gopts.noDB
added := 0
attempted := 0
if jsonInput {
fmt.Printf("detected json file. loading %d item(s)\n", len(idItems))
attempted = len(idItems)
for _, item := range idItems {
if err = mainApp.AddByID(ctx, item.Source, item.MediaType, item.ID); err != nil {
fmt.Printf("add failed: source=%s type=%s id=%s err=%v\n", item.Source, item.MediaType, item.ID, err)
@@ -113,6 +119,7 @@ func cmdFile(ctx context.Context, cfg *config.Config, gopts globalOptions, args
fmt.Printf("found %d repeated url(s)\n", repeated)
}
fmt.Printf("detected list of urls. loading %d item(s)\n", len(urls))
attempted = len(urls)
for _, raw := range urls {
if addURLToQueue(ctx, mainApp, raw) {
added++
@@ -121,6 +128,10 @@ func cmdFile(ctx context.Context, cfg *config.Config, gopts globalOptions, args
}
if added == 0 {
if attempted > 0 {
fmt.Fprintln(os.Stderr, "no valid items queued")
return 1
}
fmt.Println("nothing to rip")
return 0
}
@@ -165,6 +176,14 @@ func cmdID(ctx context.Context, cfg *config.Config, gopts globalOptions, args []
cfg.Session.Tidal.Quality = opts.quality
case "yandex":
cfg.Session.Yandex.Quality = opts.quality
case "deezer":
if opts.quality < 1 || opts.quality > 2 {
fmt.Fprintf(os.Stderr, "quality error: deezer quality must be 1-2\n")
return 2
}
cfg.Session.Deezer.Quality = opts.quality
case "soundcloud":
cfg.Session.Soundcloud.Quality = opts.quality
case "beatport":
if opts.quality < 1 {
fmt.Fprintf(os.Stderr, "quality error: beatport quality must be 1-4\n")
+26 -52
View File
@@ -120,44 +120,8 @@ func cmdSearch(ctx context.Context, cfg *config.Config, gopts globalOptions, arg
}
if sopts.first {
selection := []int{0}
mainApp.IgnoreDB = sopts.ignoreDB || gopts.noDB
skippedDownloaded := 0
added := 0
for _, idx := range selection {
item := results[idx]
if !sopts.ignoreDB {
already, checkErr := mainApp.Store.IsDownloaded(ctx, source, item.ID)
if checkErr == nil && already {
skippedDownloaded++
fmt.Printf("skip (already downloaded): id=%s | %s\n", item.ID, item.Title)
continue
}
}
if err = mainApp.AddByID(ctx, source, mediaType, item.ID); err != nil {
fmt.Printf("add failed: id=%s err=%v\n", item.ID, err)
continue
}
added++
}
if added == 0 {
if skippedDownloaded > 0 {
fmt.Println("selected item was already downloaded (use --force to redownload)")
} else {
fmt.Println("nothing selected to download")
}
return 0
}
if err = mainApp.Resolve(ctx); err != nil {
fmt.Fprintf(os.Stderr, "resolve error: %s\n", errorWithActionableHint(err, gopts))
return 1
}
if err = mainApp.Rip(ctx); err != nil {
fmt.Fprintf(os.Stderr, "rip error: %s\n", errorWithActionableHint(err, gopts))
return 1
}
fmt.Printf("search download complete (%d item(s))\n", added)
return 0
return downloadSearchSelection(ctx, mainApp, gopts, source, mediaType, results, []int{0}, sopts.ignoreDB || gopts.noDB,
"selected item was already downloaded (use --force to redownload)")
}
if !term.IsTerminal(int(os.Stdin.Fd())) {
@@ -175,12 +139,24 @@ func cmdSearch(ctx context.Context, cfg *config.Config, gopts globalOptions, arg
return 0
}
mainApp.IgnoreDB = sopts.ignoreDB || gopts.noDB
return downloadSearchSelection(ctx, mainApp, gopts, source, mediaType, results, selection, sopts.ignoreDB || gopts.noDB,
"all selected items were already downloaded (use --force to redownload)")
}
// downloadSearchSelection queues and rips the chosen search hits. The --first
// and interactive paths used to carry identical copies of this block, which
// drifted: only some of them honored --no-db. One copy keeps the skip check,
// queueing, and exit reporting consistent.
func downloadSearchSelection(ctx context.Context, mainApp *app.Main, gopts globalOptions, source, mediaType string, results []searchResult, selection []int, ignoreDB bool, skippedMessage string) int {
mainApp.IgnoreDB = ignoreDB
skippedDownloaded := 0
added := 0
for _, idx := range selection {
if idx < 0 || idx >= len(results) {
continue
}
item := results[idx]
if !sopts.ignoreDB {
if !ignoreDB {
already, checkErr := mainApp.Store.IsDownloaded(ctx, source, item.ID)
if checkErr == nil && already {
skippedDownloaded++
@@ -188,7 +164,7 @@ func cmdSearch(ctx context.Context, cfg *config.Config, gopts globalOptions, arg
continue
}
}
if err = mainApp.AddByID(ctx, source, mediaType, item.ID); err != nil {
if err := mainApp.AddByID(ctx, source, mediaType, item.ID); err != nil {
fmt.Printf("add failed: id=%s err=%v\n", item.ID, err)
continue
}
@@ -196,22 +172,21 @@ func cmdSearch(ctx context.Context, cfg *config.Config, gopts globalOptions, arg
}
if added == 0 {
if skippedDownloaded > 0 {
fmt.Println("all selected items were already downloaded (use --force to redownload)")
fmt.Println(skippedMessage)
} else {
fmt.Println("nothing selected to download")
}
return 0
}
if err = mainApp.Resolve(ctx); err != nil {
if err := mainApp.Resolve(ctx); err != nil {
fmt.Fprintf(os.Stderr, "resolve error: %s\n", errorWithActionableHint(err, gopts))
return 1
}
if err = mainApp.Rip(ctx); err != nil {
if err := mainApp.Rip(ctx); err != nil {
fmt.Fprintf(os.Stderr, "rip error: %s\n", errorWithActionableHint(err, gopts))
return 1
}
fmt.Printf("search download complete (%d item(s))\n", added)
return 0
}
@@ -248,8 +223,8 @@ func cmdLastFM(ctx context.Context, cfg *config.Config, gopts globalOptions, arg
return 1
}
if len(resolvedTracks) == 0 {
fmt.Println("no lastfm tracks resolved")
return 0
fmt.Fprintln(os.Stderr, "no lastfm tracks resolved")
return 1
}
playlistID := fmt.Sprintf("lastfm:%s", strings.ToLower(strings.ReplaceAll(title, " ", "_")))
@@ -258,14 +233,13 @@ func cmdLastFM(ctx context.Context, cfg *config.Config, gopts globalOptions, arg
refs = append(refs, app.PlaylistTrackRef{Source: item.Source, ID: item.ID})
}
if addErr := mainApp.AddMixedPlaylistByTrackRefs(ctx, playlistID, title, refs); addErr != nil {
fmt.Printf("playlist queue failed: err=%v\n", addErr)
fmt.Println("no lastfm playlists queued")
return 0
fmt.Fprintf(os.Stderr, "playlist queue failed: %v\n", addErr)
return 1
}
fmt.Printf("queued lastfm playlist: %s (%d tracks)\n", title, len(refs))
if len(refs) == 0 {
fmt.Println("no lastfm playlists queued")
return 0
fmt.Fprintln(os.Stderr, "no lastfm playlists queued")
return 1
}
if err = mainApp.Resolve(ctx); err != nil {
fmt.Fprintf(os.Stderr, "resolve error: %v\n", err)
+17
View File
@@ -7,6 +7,7 @@ import (
"strings"
"streamrip-go/internal/app"
"streamrip-go/internal/audio/convert"
"streamrip-go/internal/config"
"streamrip-go/internal/jsonutil"
"streamrip-go/internal/provider"
@@ -92,6 +93,22 @@ func cmdQobuzConvertRipSmoke(ctx context.Context, cfg *config.Config, gopts glob
}
cfg.Session.Conversion.Enabled = true
cfg.Session.Conversion.Codec = strings.ToUpper(strings.TrimSpace(args[1]))
if !convert.SupportsCodec(cfg.Session.Conversion.Codec) {
fmt.Fprintf(os.Stderr, "codec error: unsupported conversion codec %q\n", cfg.Session.Conversion.Codec)
return 2
}
// A smoke test must not touch the real library: write into a throwaway
// folder and disable the databases so downloads are not recorded.
smokeDir, err := os.MkdirTemp("", "streamrip-qobuz-convert-smoke-*")
if err != nil {
fmt.Fprintf(os.Stderr, "temp dir error: %v\n", err)
return 1
}
defer func() { _ = os.RemoveAll(smokeDir) }()
cfg.Session.Downloads.Folder = smokeDir
cfg.Session.Database.DownloadsEnabled = false
cfg.Session.Database.FailedDownloadsEnabled = false
mainApp, err := app.New(cfg)
if err != nil {
+5 -5
View File
@@ -101,14 +101,14 @@ func TestCmdFileRejectsUnknownOption(t *testing.T) {
}
func TestCmdURLRejectsInvalidURL(t *testing.T) {
// Nothing resolvable is queued, so this reports "nothing to rip" and exits 0.
// Nothing resolvable is queued: the command must not report success.
out := captureStdout(t, func() {
if got := cmdURL(context.Background(), testConfig(t), globalOptions{}, []string{"not-a-url"}); got != 0 {
t.Errorf("exit code = %d, want 0", got)
if got := cmdURL(context.Background(), testConfig(t), globalOptions{}, []string{"not-a-url"}); got != 1 {
t.Errorf("exit code = %d, want 1", got)
}
})
if !strings.Contains(out, "nothing to rip") {
t.Fatalf("output %q should report that nothing was queued", out)
if !strings.Contains(out, "invalid: not-a-url") {
t.Fatalf("output %q should report the invalid url", out)
}
}
+4
View File
@@ -119,6 +119,10 @@ Import a Last.fm playlist and resolve tracks through configured providers.
Options:
--source SOURCE Primary lookup source
--fallback-source SOURCE Fallback lookup source
If last.fm blocks the direct request, the playlist is fetched through the
third-party r.jina.ai mirror. Set STREAMRIP_GO_DISABLE_LASTFM_MIRROR=1 to
disable that fallback.
`)
case "config":
fmt.Fprint(w, `Usage:
+14 -2
View File
@@ -6,6 +6,7 @@ import (
"database/sql"
"encoding/json"
"fmt"
"net/url"
"os"
"os/exec"
"regexp"
@@ -176,8 +177,19 @@ func openConfigInEditor(path string, vim bool) error {
}
}
// openReadOnlySQLite opens path in SQLite read-only mode. `rip database
// browse` must not create WAL/journal files or take a write lock on a library
// that a rip may be writing at the same time.
func openReadOnlySQLite(path string) (*sql.DB, error) {
u := url.URL{Scheme: "file", Opaque: (&url.URL{Path: path}).EscapedPath()}
q := url.Values{}
q.Set("mode", "ro")
q.Add("_pragma", "busy_timeout(10000)")
return sql.Open("sqlite", u.String()+"?"+q.Encode())
}
func listDownloadsRows(path string) ([]string, error) {
db, err := sql.Open("sqlite", path)
db, err := openReadOnlySQLite(path)
if err != nil {
return nil, err
}
@@ -204,7 +216,7 @@ func listDownloadsRows(path string) ([]string, error) {
}
func listFailedRows(path string) ([]failedRow, error) {
db, err := sql.Open("sqlite", path)
db, err := openReadOnlySQLite(path)
if err != nil {
return nil, err
}
+23 -2
View File
@@ -8,6 +8,7 @@ import (
"io"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
@@ -91,11 +92,11 @@ func fetchLastFMPlaylist(ctx context.Context, verifySSL bool, playlistURL string
page1, err := fetchLastFMPlaylistPage(ctx, client, parsed, 1)
if err != nil {
return fetchLastFMPlaylistViaMirror(ctx, verifySSL, playlistURL)
return lastFMPlaylistFallback(ctx, verifySSL, playlistURL, err)
}
title, total, err := extractLastFMPlaylistInfo(page1)
if err != nil {
return fetchLastFMPlaylistViaMirror(ctx, verifySSL, playlistURL)
return lastFMPlaylistFallback(ctx, verifySSL, playlistURL, err)
}
tracks := extractLastFMTitleArtistPairs(page1)
if total <= len(tracks) || total <= 50 {
@@ -123,6 +124,26 @@ func fetchLastFMPlaylist(ctx context.Context, verifySSL bool, playlistURL string
return title, tracks, nil
}
func lastFMMirrorDisabled() bool {
switch strings.ToLower(strings.TrimSpace(os.Getenv("STREAMRIP_GO_DISABLE_LASTFM_MIRROR"))) {
case "1", "true", "yes", "on":
return true
}
return false
}
func lastFMPlaylistFallback(ctx context.Context, verifySSL bool, playlistURL string, directErr error) (string, []lastFMTrack, error) {
if lastFMMirrorDisabled() {
return "", nil, directErr
}
fmt.Fprintf(os.Stderr, "lastfm: direct fetch failed (%v); retrying through the third-party r.jina.ai mirror, which receives the playlist URL (set STREAMRIP_GO_DISABLE_LASTFM_MIRROR=1 to disable)\n", directErr)
title, tracks, err := fetchLastFMPlaylistViaMirror(ctx, verifySSL, playlistURL)
if err != nil {
return "", nil, fmt.Errorf("direct fetch failed: %v; mirror failed: %w", directErr, err)
}
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)
+44 -3
View File
@@ -41,6 +41,11 @@ type Main struct {
IgnoreDB bool
Pending []media.Pending
Media []media.Media
// claimMu guards claimedPaths, which keeps two tracks that format to the
// same file name from silently overwriting each other in one run.
claimMu sync.Mutex
claimedPaths map[string]struct{}
}
type PlaylistTrackRef struct {
@@ -129,7 +134,11 @@ func New(cfg *config.Config) (*Main, error) {
if err != nil {
return nil, err
}
db = s
db = &store.FeatureFlags{
DB: s,
DownloadsEnabled: cfg.Session.Database.DownloadsEnabled,
FailedEnabled: cfg.Session.Database.FailedDownloadsEnabled,
}
} else {
db = store.NewDummy()
}
@@ -608,6 +617,7 @@ func (m *Main) ripTrackCollection(ctx context.Context, p provider.Client, source
})
if failures > 0 {
m.logf("%s done with %d failed track(s)\n", kind, failures)
return fmt.Errorf("%s: %d track(s) failed", kind, failures)
}
return nil
}
@@ -904,6 +914,7 @@ func (m *Main) ripAlbum(ctx context.Context, p provider.Client, source, albumID
})
if failures > 0 {
m.logf("Album done with %d failed track(s)\n", failures)
return fmt.Errorf("album: %d track(s) failed", failures)
}
return nil
}
@@ -966,6 +977,7 @@ func (m *Main) ripPlaylist(ctx context.Context, p provider.Client, source, playl
if failures > 0 {
m.logf("Playlist done with %d failed track(s)\n", failures)
return fmt.Errorf("playlist: %d track(s) failed", failures)
}
return nil
}
@@ -1030,6 +1042,7 @@ func (m *Main) ripPlaylistMixed(ctx context.Context, playlistID, name string, re
if failures > 0 {
m.logf("Playlist done with %d failed track(s)\n", failures)
return fmt.Errorf("playlist: %d track(s) failed", failures)
}
return nil
}
@@ -1407,7 +1420,7 @@ func (m *Main) trackOutputPath(source, id, title, ext string, d *provider.Downlo
RestrictCharacters: m.Config.Session.Filepaths.RestrictCharacters,
TruncateTo: m.Config.Session.Filepaths.TruncateTo,
})
return m.safeJoin(base, fileName+"."+ext)
return m.claimOutputPath(m.safeJoin(base, fileName+"."+ext))
}
func (m *Main) videoOutputPath(source, id, title, ext string) string {
@@ -1425,7 +1438,35 @@ func (m *Main) videoOutputPath(source, id, title, ext string) string {
if fileName == "" {
fileName = id
}
return m.safeJoin(base, fileName+"."+ext)
return m.claimOutputPath(m.safeJoin(base, fileName+"."+ext))
}
// claimOutputPath reserves path for the duration of this run and returns a
// free variant if another track already claimed it. Track templates that omit
// the track number, or albums with duplicate positions, would otherwise map
// two tracks to one file and silently overwrite the first download.
func (m *Main) claimOutputPath(path string) string {
m.claimMu.Lock()
defer m.claimMu.Unlock()
if m.claimedPaths == nil {
m.claimedPaths = make(map[string]struct{})
}
if _, taken := m.claimedPaths[path]; !taken {
m.claimedPaths[path] = struct{}{}
return path
}
ext := filepath.Ext(path)
stem := strings.TrimSuffix(path, ext)
for i := 2; i < 10000; i++ {
candidate := fmt.Sprintf("%s (%d)%s", stem, i, ext)
if _, taken := m.claimedPaths[candidate]; taken {
continue
}
m.claimedPaths[candidate] = struct{}{}
return candidate
}
m.logf("warning: too many file name collisions for %q; overwriting\n", path)
return path
}
func titleFromMetadata(meta map[string]any, fallback string) string {
+9
View File
@@ -28,6 +28,15 @@ var profiles = map[string]profile{
"AAC": {codecLib: "aac", ext: "m4a", lossless: false},
}
// SupportsCodec reports whether codec names a conversion target this build can
// produce. Callers that accept a codec from the command line should check this
// before starting a download, so an invalid target fails immediately instead of
// after the audio has been fetched.
func SupportsCodec(codec string) bool {
_, ok := profiles[strings.ToUpper(strings.TrimSpace(codec))]
return ok
}
func Convert(ctx context.Context, path string, cfg config.ConversionConfig) (string, error) {
if !cfg.Enabled {
return path, nil
+32 -4
View File
@@ -133,8 +133,12 @@ type SoundcloudConfig struct {
}
type DatabaseConfig struct {
DownloadsEnabled bool `toml:"downloads_enabled"`
DownloadsPath string `toml:"downloads_path"`
DownloadsEnabled bool `toml:"downloads_enabled"`
DownloadsPath string `toml:"downloads_path"`
// FailedDownloadsEnabled controls whether failures are recorded at all.
// FailedDownloadsPath is deprecated: this program stores the
// failed_downloads table in DownloadsPath. It is kept so existing config
// files still load.
FailedDownloadsEnabled bool `toml:"failed_downloads_enabled"`
FailedDownloadsPath string `toml:"failed_downloads_path"`
}
@@ -555,14 +559,38 @@ func defaultAppDir() string {
func saveConfigData(path string, data ConfigData) error {
// 0o700/0o600: this file holds plaintext provider passwords, Deezer ARL
// cookies and OAuth access/refresh tokens, so it must not be world-readable.
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
dir := filepath.Dir(path)
if err := os.MkdirAll(dir, 0o700); err != nil {
return err
}
b, err := toml.Marshal(data)
if err != nil {
return err
}
if err := os.WriteFile(path, b, 0o600); err != nil {
// Write to a sibling and rename so a crash or full disk cannot leave a
// truncated config behind; the old file stays intact until the rename.
tmp, err := os.CreateTemp(dir, ".config-*.tmp")
if err != nil {
return err
}
tmpPath := tmp.Name()
defer func() { _ = os.Remove(tmpPath) }()
if err = tmp.Chmod(0o600); err != nil {
_ = tmp.Close()
return err
}
if _, err = tmp.Write(b); err != nil {
_ = tmp.Close()
return err
}
if err = tmp.Sync(); err != nil {
_ = tmp.Close()
return err
}
if err = tmp.Close(); err != nil {
return err
}
if err = os.Rename(tmpPath, path); err != nil {
return err
}
// Tighten an existing file that a previous version created as 0o644.
+4 -4
View File
@@ -93,7 +93,7 @@ func (d *Downloader) streamEncrypted(
if err != nil {
return err
}
resp, err := d.http.Do(req)
resp, err := netutil.Do(d.http, req)
if err != nil {
return err
}
@@ -209,7 +209,7 @@ func (d *Downloader) file(ctx context.Context, sourceURL, outputPath string, all
return err
}
resp, err := d.http.Do(req)
resp, err := netutil.Do(d.http, req)
if err != nil {
return err
}
@@ -276,7 +276,7 @@ func (d *Downloader) Logf(format string, args ...any) {
_, _ = d.progress.Write([]byte(msg))
return
}
fmt.Print(msg)
fmt.Fprint(os.Stderr, msg)
}
// copyWithProgress copies src to dst, reporting progress to bar when it is
@@ -372,7 +372,7 @@ func logDownloadStart(sourceURL, outputPath string) {
if !verbose.Enabled(verbose.V) {
return
}
verbose.Printf(verbose.V, "download %s -> %s\n", sourceURL, filepath.Base(outputPath))
verbose.Printf(verbose.V, "download %s -> %s\n", netutil.RedactURLString(sourceURL), filepath.Base(outputPath))
}
func shortenName(name string, max int) string {
+76 -14
View File
@@ -47,6 +47,56 @@ func NewHTTPClient(timeout time.Duration, verifySSL bool, maxConnsPerHost int) *
}
}
// Do performs req and sanitizes transport errors before returning them.
//
// http.Client.Do wraps transport failures in *url.Error, whose Error() method
// embeds the full request URL. Several providers put credentials in query
// parameters (qobuz password/user_auth_token, deezer api_key/sid, yandex
// sign), so returning that error verbatim would print the secret to the
// terminal and into failure logs. Callers should use this instead of
// client.Do directly.
func Do(client *http.Client, req *http.Request) (*http.Response, error) {
resp, err := client.Do(req)
if err == nil {
return resp, nil
}
return resp, RedactError(err)
}
// RedactError returns err with credentials in its URL removed. It only
// rewrites a top-level *url.Error, which is what http.Client.Do returns;
// other error types are returned unchanged.
func RedactError(err error) error {
if err == nil {
return nil
}
uerr, ok := err.(*url.Error)
if !ok {
return err
}
u, parseErr := url.Parse(uerr.URL)
if parseErr != nil {
return err
}
redacted := redactURL(u)
if redacted == uerr.URL {
return err
}
cp := *uerr
cp.URL = redacted
return &cp
}
// RedactURLString is the string form of redactURL, for logging URLs that are
// already serialized (download URLs, error messages).
func RedactURLString(raw string) string {
u, err := url.Parse(raw)
if err != nil {
return raw
}
return redactURL(u)
}
// loggingTransport emits one verbose line per HTTP request when verbose
// level >= VV. The check is per-call so toggling the level at runtime
// affects subsequent requests without rebuilding clients.
@@ -71,34 +121,46 @@ func (t *loggingTransport) RoundTrip(req *http.Request) (*http.Response, error)
}
// redactURL hides values for query parameters that commonly carry
// credentials so -vv output is safe to paste in an issue.
// credentials so -vv output and transport errors are safe to paste in an
// issue. Userinfo passwords are redacted as well.
func redactURL(u *url.URL) string {
if u == nil {
return ""
}
if u.RawQuery == "" {
return u.String()
}
q := u.Query()
redacted := false
for k := range q {
if isSensitiveParam(k) {
q.Set(k, "REDACTED")
redacted = true
cp := *u
changed := false
if cp.User != nil {
if _, hasPassword := cp.User.Password(); hasPassword {
cp.User = url.UserPassword(cp.User.Username(), "REDACTED")
changed = true
}
}
if !redacted {
if cp.RawQuery != "" {
q := cp.Query()
redactedQuery := false
for k := range q {
if isSensitiveParam(k) {
q.Set(k, "REDACTED")
redactedQuery = true
}
}
if redactedQuery {
cp.RawQuery = q.Encode()
changed = true
}
}
if !changed {
return u.String()
}
cp := *u
cp.RawQuery = q.Encode()
return cp.String()
}
func isSensitiveParam(name string) bool {
switch name {
case "user_auth_token", "api_token", "access_token", "refresh_token",
"request_sig", "signature", "password", "secret", "token", "code", "auth", "key":
"request_sig", "signature", "sign", "password", "pass", "pwd",
"secret", "app_secret", "client_secret", "token", "code", "auth",
"key", "api_key", "sid", "arl":
return true
}
return false
+27 -13
View File
@@ -162,6 +162,7 @@ func (c *Client) Search(ctx context.Context, mediaType, query string, limit int)
params.Set("q", query)
params.Set("order_by", "-publish_date")
params.Set("is_available_for_streaming", "true")
params.Set("per_page", strconv.Itoa(limit))
resp, err := c.getMap(ctx, "/catalog/search/", params)
if err != nil {
return nil, err
@@ -300,10 +301,11 @@ func (c *Client) getMap(ctx context.Context, endpoint string, params url.Values)
}
func (c *Client) apiRequest(ctx context.Context, method, endpoint string, params url.Values, payload any, contentType string) (map[string]any, error) {
if err := c.ensureToken(ctx); err != nil {
token, err := c.ensureToken(ctx)
if err != nil {
return nil, err
}
resp, status, err := c.rawRequest(ctx, method, endpoint, params, payload, contentType, true)
resp, status, err := c.rawRequest(ctx, method, endpoint, params, payload, contentType, token)
if err != nil {
return nil, err
}
@@ -311,7 +313,7 @@ func (c *Client) apiRequest(ctx context.Context, method, endpoint string, params
if err = c.reauthorize(ctx); err != nil {
return nil, err
}
resp, status, err = c.rawRequest(ctx, method, endpoint, params, payload, contentType, true)
resp, status, err = c.rawRequest(ctx, method, endpoint, params, payload, contentType, c.accessToken())
if err != nil {
return nil, err
}
@@ -322,10 +324,22 @@ func (c *Client) apiRequest(ctx context.Context, method, endpoint string, params
return resp, nil
}
func (c *Client) ensureToken(ctx context.Context) error {
// ensureToken makes sure a token is available and returns it. The token is
// snapshotted while authMu is held so rawRequest never reads config state
// that a concurrent refresh is rewriting.
func (c *Client) ensureToken(ctx context.Context) (string, error) {
c.authMu.Lock()
defer c.authMu.Unlock()
return c.ensureTokenLocked(ctx)
if err := c.ensureTokenLocked(ctx); err != nil {
return "", err
}
return strings.TrimSpace(c.cfg.Session.Beatport.AccessToken), nil
}
func (c *Client) accessToken() string {
c.authMu.Lock()
defer c.authMu.Unlock()
return strings.TrimSpace(c.cfg.Session.Beatport.AccessToken)
}
// ensureTokenLocked requires c.authMu to be held.
@@ -350,7 +364,7 @@ func (c *Client) reauthorize(ctx context.Context) error {
c.cfg.Session.Beatport.TokenExpiry = 0
if err := c.refresh(ctx); err != nil {
if loginErr := c.loginPasswordFlow(ctx); loginErr != nil {
return err
return fmt.Errorf("beatport reauthorize failed: refresh: %v; login: %w", err, loginErr)
}
}
return nil
@@ -361,7 +375,7 @@ func (c *Client) loginPasswordFlow(ctx context.Context) error {
if strings.TrimSpace(b.Username) == "" || strings.TrimSpace(b.Password) == "" {
return errMissingCredentials
}
loginResp, status, err := c.rawRequest(ctx, http.MethodPost, loginEndpoint, nil, map[string]string{"username": b.Username, "password": b.Password}, "application/json", false)
loginResp, status, err := c.rawRequest(ctx, http.MethodPost, loginEndpoint, nil, map[string]string{"username": b.Username, "password": b.Password}, "application/json", "")
if err != nil {
return err
}
@@ -380,7 +394,7 @@ func (c *Client) loginPasswordFlow(ctx context.Context) error {
func (c *Client) authorize(ctx context.Context) (string, error) {
params := url.Values{"client_id": []string{c.appClientID()}, "response_type": []string{"code"}}
resp, status, err := c.rawRequest(ctx, http.MethodGet, authEndpoint, params, nil, "", false)
resp, status, err := c.rawRequest(ctx, http.MethodGet, authEndpoint, params, nil, "", "")
if err != nil {
return "", err
}
@@ -400,7 +414,7 @@ func (c *Client) refresh(ctx context.Context) error {
}
func (c *Client) issueToken(ctx context.Context, payload map[string]string) error {
resp, status, err := c.rawRequest(ctx, http.MethodPost, tokenEndpoint, nil, payload, "application/x-www-form-urlencoded", false)
resp, status, err := c.rawRequest(ctx, http.MethodPost, tokenEndpoint, nil, payload, "application/x-www-form-urlencoded", "")
if err != nil {
return err
}
@@ -432,7 +446,7 @@ func (c *Client) issueToken(ctx context.Context, payload map[string]string) erro
return nil
}
func (c *Client) rawRequest(ctx context.Context, method, endpoint string, params url.Values, payload any, contentType string, auth bool) (map[string]any, int, error) {
func (c *Client) rawRequest(ctx context.Context, method, endpoint string, params url.Values, payload any, contentType string, token string) (map[string]any, int, error) {
if c.limiter != nil {
if err := c.limiter.Wait(ctx); err != nil {
return nil, 0, err
@@ -473,13 +487,13 @@ func (c *Client) rawRequest(ctx context.Context, method, endpoint string, params
if contentType != "" {
req.Header.Set("Content-Type", contentType)
}
if auth && strings.TrimSpace(c.cfg.Session.Beatport.AccessToken) != "" {
req.Header.Set("Authorization", "Bearer "+strings.TrimSpace(c.cfg.Session.Beatport.AccessToken))
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
if endpoint == authEndpoint && c.sessionID != "" {
req.Header.Set("Cookie", "sessionid="+c.sessionID)
}
resp, err := c.http.Do(req)
resp, err := netutil.Do(c.http, req)
if err != nil {
return nil, 0, err
}
+123 -53
View File
@@ -50,10 +50,15 @@ type Client struct {
cfg *config.Config
http *http.Client
limiter *ratelimit.Limiter
// authMu guards loggedIn and the login/refresh path, which download
// workers can reach concurrently.
// authMu guards loggedIn and serializes Login calls. It is the outer
// lock: when both are needed, take authMu before stateMu.
authMu sync.Mutex
loggedIn bool
// stateMu guards the auth token fields below. Download workers and the
// lyrics path reach refreshes concurrently, so every read or write of
// the token group holds it. Functions ending in "Locked" require
// stateMu to be held.
stateMu sync.Mutex
ua string
deviceID string
sid string
@@ -87,13 +92,15 @@ func (c *Client) Source() string {
func (c *Client) Login(ctx context.Context) error {
c.authMu.Lock()
defer c.authMu.Unlock()
c.stateMu.Lock()
defer c.stateMu.Unlock()
c.arl = strings.TrimSpace(c.cfg.Session.Deezer.ARL)
c.sid = ""
c.jwt = ""
c.refresh = strings.TrimSpace(c.cfg.Session.Deezer.RefreshToken)
c.license = ""
c.userID = ""
if err := c.ensureLaunchSession(ctx); err != nil {
if err := c.ensureLaunchSessionLocked(ctx); err != nil {
return err
}
c.loggedIn = true
@@ -101,23 +108,45 @@ func (c *Client) Login(ctx context.Context) error {
}
func (c *Client) ensureLaunchSession(ctx context.Context) error {
c.stateMu.Lock()
defer c.stateMu.Unlock()
return c.ensureLaunchSessionLocked(ctx)
}
func (c *Client) ensureLaunchSessionLocked(ctx context.Context) error {
email := strings.TrimSpace(c.cfg.Session.Deezer.Email)
password := strings.TrimSpace(c.cfg.Session.Deezer.Password)
if strings.TrimSpace(c.arl) != "" {
return c.refreshSessionFromARL(ctx)
return c.refreshSessionFromARLLocked(ctx)
}
if email != "" && password != "" {
return c.loginWithCredentials(ctx, email, password)
return c.loginWithCredentialsLocked(ctx, email, password)
}
if strings.TrimSpace(c.refresh) != "" {
if err := c.refreshJWT(ctx); err != nil {
if err := c.refreshJWTLocked(ctx); err != nil {
return err
}
return c.refreshLicenseFromPipe(ctx)
return c.refreshLicenseFromPipeLocked(ctx)
}
return errors.New("deezer login requires deezer.arl, deezer.email+deezer.password, or deezer.refresh_token")
}
// ensureLicense makes sure a usable media license token is present.
func (c *Client) ensureLicense(ctx context.Context) error {
c.stateMu.Lock()
defer c.stateMu.Unlock()
if strings.TrimSpace(c.license) != "" {
return nil
}
if err := c.ensureLaunchSessionLocked(ctx); err != nil {
return err
}
if strings.TrimSpace(c.license) == "" {
return errors.New("deezer native download requires deezer.arl, deezer.email+deezer.password, or deezer.refresh_token")
}
return nil
}
func (c *Client) LoggedIn() bool {
c.authMu.Lock()
defer c.authMu.Unlock()
@@ -183,9 +212,11 @@ func (c *Client) GetMetadata(ctx context.Context, item, mediaType string) (map[s
if err != nil {
return nil, err
}
if tracks, pageErr := c.getCollectionPageItems(ctx, "/album/"+strings.TrimSpace(item)+"/tracks"); pageErr == nil {
resp["tracks"] = map[string]any{"data": tracks}
tracks, err := c.getCollectionPageItems(ctx, "/album/"+strings.TrimSpace(item)+"/tracks")
if err != nil {
return nil, fmt.Errorf("deezer album tracks: %w", err)
}
resp["tracks"] = map[string]any{"data": tracks}
items := make([]any, 0)
if tracks, ok := resp["tracks"].(map[string]any); ok {
if data, ok := tracks["data"].([]any); ok {
@@ -207,9 +238,11 @@ func (c *Client) GetMetadata(ctx context.Context, item, mediaType string) (map[s
if err != nil {
return nil, err
}
if tracks, pageErr := c.getCollectionPageItems(ctx, "/playlist/"+strings.TrimSpace(item)+"/tracks"); pageErr == nil {
resp["tracks"] = map[string]any{"data": tracks}
tracks, err := c.getCollectionPageItems(ctx, "/playlist/"+strings.TrimSpace(item)+"/tracks")
if err != nil {
return nil, fmt.Errorf("deezer playlist tracks: %w", err)
}
resp["tracks"] = map[string]any{"data": tracks}
items := make([]any, 0)
if tracks, ok := resp["tracks"].(map[string]any); ok {
if data, ok := tracks["data"].([]any); ok {
@@ -312,18 +345,11 @@ func (c *Client) getCollectionPageItems(ctx context.Context, path string) ([]any
}
func (c *Client) GetDownloadable(ctx context.Context, item string, _ int) (*provider.Downloadable, error) {
if strings.TrimSpace(c.license) == "" {
if err := c.ensureLaunchSession(ctx); err != nil {
return nil, err
}
}
if strings.TrimSpace(c.license) == "" {
return nil, errors.New("deezer native download requires deezer.arl, deezer.email+deezer.password, or deezer.refresh_token")
}
meta, err := c.GetMetadata(ctx, item, "track")
if err != nil {
if err := c.ensureLicense(ctx); err != nil {
return nil, err
}
// The caller already fetched track metadata before asking for the
// download; only the media token lookup is needed here.
trackToken, mediaTrackID, err := c.getTrackToken(ctx, item)
if err != nil {
return nil, err
@@ -340,9 +366,6 @@ func (c *Client) GetDownloadable(ctx context.Context, item string, _ int) (*prov
if trackID == "" {
trackID = strings.TrimSpace(mediaTrackID)
}
if trackID == "" {
trackID = strings.TrimSpace(jsonutil.StringFromAny(meta["id"]))
}
if trackID == "" {
trackID = strings.TrimSpace(item)
}
@@ -371,7 +394,7 @@ func (c *Client) apiGet(ctx context.Context, path string, params url.Values) (ma
}
req.Header.Set("User-Agent", "streamrip-go/0.1")
resp, err := c.http.Do(req)
resp, err := netutil.Do(c.http, req)
if err != nil {
return nil, err
}
@@ -403,6 +426,12 @@ func (c *Client) apiGet(ctx context.Context, path string, params url.Values) (ma
}
func (c *Client) refreshSessionFromARL(ctx context.Context) error {
c.stateMu.Lock()
defer c.stateMu.Unlock()
return c.refreshSessionFromARLLocked(ctx)
}
func (c *Client) refreshSessionFromARLLocked(ctx context.Context) error {
if strings.TrimSpace(c.arl) == "" {
return errors.New("missing deezer arl")
}
@@ -423,7 +452,7 @@ func (c *Client) refreshSessionFromARL(ctx context.Context) error {
req.Header.Set("Accept", "application/json")
req.Header.Set("Cookie", "arl="+strings.TrimSpace(c.arl))
resp, err := c.http.Do(req)
resp, err := netutil.Do(c.http, req)
if err != nil {
return err
}
@@ -455,13 +484,13 @@ func (c *Client) refreshSessionFromARL(ctx context.Context) error {
c.sid = sid
}
if c.sid != "" && c.userID != "" {
_ = c.mobileUserAutolog(ctx)
_ = c.mobileUserAutologLocked(ctx)
}
if c.jwt == "" && c.refresh != "" {
_ = c.refreshJWT(ctx)
_ = c.refreshJWTLocked(ctx)
}
if c.jwt != "" {
_ = c.refreshLicenseFromPipe(ctx)
_ = c.refreshLicenseFromPipeLocked(ctx)
}
if c.license == "" {
return errors.New("deezer getUserData missing license_token")
@@ -487,6 +516,12 @@ func (c *Client) persistRefreshToken() {
}
func (c *Client) loginWithCredentials(ctx context.Context, email, password string) error {
c.stateMu.Lock()
defer c.stateMu.Unlock()
return c.loginWithCredentialsLocked(ctx, email, password)
}
func (c *Client) loginWithCredentialsLocked(ctx context.Context, email, password string) error {
email = strings.TrimSpace(email)
password = strings.TrimSpace(password)
if email == "" || password == "" {
@@ -542,7 +577,7 @@ func (c *Client) loginWithCredentials(ctx context.Context, email, password strin
req.Header.Set("Accept", "application/json")
req.Header.Set("Content-Type", "application/json; charset=utf-8")
resp, err := c.http.Do(req)
resp, err := netutil.Do(c.http, req)
if err != nil {
return err
}
@@ -582,13 +617,13 @@ func (c *Client) loginWithCredentials(ctx context.Context, email, password strin
}
if c.license == "" {
if c.jwt == "" && c.refresh != "" {
_ = c.refreshJWT(ctx)
_ = c.refreshJWTLocked(ctx)
}
if c.jwt != "" {
_ = c.refreshLicenseFromPipe(ctx)
_ = c.refreshLicenseFromPipeLocked(ctx)
}
if c.license == "" {
_ = c.refreshSessionFromARL(ctx)
_ = c.refreshSessionFromARLLocked(ctx)
}
}
if c.license == "" {
@@ -696,11 +731,12 @@ func (c *Client) fetchLyricsFromPipe(ctx context.Context, trackID string) (*lyri
if err := c.ensureJWT(ctx, "deezer jwt unavailable for lyrics query"); err != nil {
return nil, err
}
res, err := fetchOnce(c.jwt)
jwt := c.currentJWT()
res, err := fetchOnce(jwt)
if errors.Is(err, errDeezerJWTExpired) {
c.refreshJWTFromAvailableState(ctx)
if strings.TrimSpace(c.jwt) != "" {
return fetchOnce(c.jwt)
if jwt = c.currentJWT(); strings.TrimSpace(jwt) != "" {
return fetchOnce(jwt)
}
}
return res, err
@@ -765,7 +801,7 @@ func (c *Client) mobileAuth(ctx context.Context) (string, error) {
req.Header.Set("User-Agent", c.ua)
req.Header.Set("Accept", "application/json")
resp, err := c.http.Do(req)
resp, err := netutil.Do(c.http, req)
if err != nil {
return "", err
}
@@ -812,7 +848,7 @@ func (c *Client) apiCheckToken(ctx context.Context, authToken string) (string, e
}
req.Header.Set("User-Agent", c.ua)
req.Header.Set("Accept", "application/json")
resp, err := c.http.Do(req)
resp, err := netutil.Do(c.http, req)
if err != nil {
return "", err
}
@@ -843,6 +879,12 @@ func (c *Client) apiCheckToken(ctx context.Context, authToken string) (string, e
}
func (c *Client) mobileUserAutolog(ctx context.Context) error {
c.stateMu.Lock()
defer c.stateMu.Unlock()
return c.mobileUserAutologLocked(ctx)
}
func (c *Client) mobileUserAutologLocked(ctx context.Context) error {
if c.sid == "" || c.userID == "" || c.arl == "" {
return errors.New("mobile_userAutolog requires sid, user id, and arl")
}
@@ -882,7 +924,7 @@ func (c *Client) mobileUserAutolog(ctx context.Context) error {
req.Header.Set("User-Agent", c.ua)
req.Header.Set("Accept", "application/json")
req.Header.Set("Content-Type", "application/json; charset=utf-8")
resp, err := c.http.Do(req)
resp, err := netutil.Do(c.http, req)
if err != nil {
continue
}
@@ -910,6 +952,12 @@ func (c *Client) mobileUserAutolog(ctx context.Context) error {
}
func (c *Client) refreshJWT(ctx context.Context) error {
c.stateMu.Lock()
defer c.stateMu.Unlock()
return c.refreshJWTLocked(ctx)
}
func (c *Client) refreshJWTLocked(ctx context.Context) error {
if strings.TrimSpace(c.refresh) == "" {
return errors.New("missing deezer refresh token")
}
@@ -924,7 +972,7 @@ func (c *Client) refreshJWT(ctx context.Context) error {
}
req.Header.Set("User-Agent", c.ua)
req.Header.Set("Content-Type", "application/json; charset=utf-8")
resp, err := c.http.Do(req)
resp, err := netutil.Do(c.http, req)
if err != nil {
return err
}
@@ -958,14 +1006,16 @@ func (c *Client) refreshJWT(ctx context.Context) error {
}
func (c *Client) ensureJWT(ctx context.Context, unavailableMsg string) error {
c.stateMu.Lock()
defer c.stateMu.Unlock()
if strings.TrimSpace(c.jwt) != "" {
return nil
}
if strings.TrimSpace(c.arl) != "" {
_ = c.refreshSessionFromARL(ctx)
_ = c.refreshSessionFromARLLocked(ctx)
}
if strings.TrimSpace(c.jwt) == "" && strings.TrimSpace(c.refresh) != "" {
_ = c.refreshJWT(ctx)
_ = c.refreshJWTLocked(ctx)
}
if strings.TrimSpace(c.jwt) == "" {
if strings.TrimSpace(unavailableMsg) == "" {
@@ -977,16 +1027,25 @@ func (c *Client) ensureJWT(ctx context.Context, unavailableMsg string) error {
}
func (c *Client) refreshJWTFromAvailableState(ctx context.Context) {
c.stateMu.Lock()
defer c.stateMu.Unlock()
if strings.TrimSpace(c.refresh) != "" {
_ = c.refreshJWT(ctx)
_ = c.refreshJWTLocked(ctx)
}
if strings.TrimSpace(c.jwt) == "" && strings.TrimSpace(c.arl) != "" {
_ = c.refreshSessionFromARL(ctx)
_ = c.refreshSessionFromARLLocked(ctx)
}
}
// currentJWT returns a snapshot of the JWT under the state lock.
func (c *Client) currentJWT() string {
c.stateMu.Lock()
defer c.stateMu.Unlock()
return c.jwt
}
func (c *Client) pipeGraphQL(ctx context.Context, body map[string]any, operation string) (map[string]any, error) {
return c.pipeGraphQLWithJWT(ctx, c.jwt, body, operation)
return c.pipeGraphQLWithJWT(ctx, c.currentJWT(), body, operation)
}
func (c *Client) pipeGraphQLWithJWT(ctx context.Context, jwt string, body map[string]any, operation string) (map[string]any, error) {
@@ -1012,7 +1071,7 @@ func (c *Client) pipeGraphQLWithJWT(ctx context.Context, jwt string, body map[st
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+jwt)
resp, err := c.http.Do(req)
resp, err := netutil.Do(c.http, req)
if err != nil {
return nil, err
}
@@ -1050,6 +1109,12 @@ func (c *Client) pipeGraphQLWithJWT(ctx context.Context, jwt string, body map[st
}
func (c *Client) refreshLicenseFromPipe(ctx context.Context) error {
c.stateMu.Lock()
defer c.stateMu.Unlock()
return c.refreshLicenseFromPipeLocked(ctx)
}
func (c *Client) refreshLicenseFromPipeLocked(ctx context.Context) error {
body := map[string]any{
"operationName": "KmpMpMediaServiceLicenseToken",
"query": "query KmpMpMediaServiceLicenseToken { tokens { mediaServiceLicenseToken { token expirationDate } } }",
@@ -1061,7 +1126,7 @@ func (c *Client) refreshLicenseFromPipe(ctx context.Context) error {
},
},
}
out, err := c.pipeGraphQL(ctx, body, "pipe license refresh")
out, err := c.pipeGraphQLWithJWT(ctx, c.jwt, body, "pipe license refresh")
if err != nil {
return err
}
@@ -1234,23 +1299,28 @@ func (c *Client) getMediaURL(ctx context.Context, trackToken string, quality int
}
func (c *Client) forceMobileLaunchRefresh(ctx context.Context) error {
c.stateMu.Lock()
defer c.stateMu.Unlock()
if strings.TrimSpace(c.arl) != "" {
c.sid = ""
c.jwt = ""
c.license = ""
return c.refreshSessionFromARL(ctx)
return c.refreshSessionFromARLLocked(ctx)
}
if strings.TrimSpace(c.refresh) != "" {
if err := c.refreshJWT(ctx); err != nil {
if err := c.refreshJWTLocked(ctx); err != nil {
return err
}
return c.refreshLicenseFromPipe(ctx)
return c.refreshLicenseFromPipeLocked(ctx)
}
return errors.New("deezer launch refresh requires arl or refresh token")
}
func (c *Client) getMediaURLWithRequest(ctx context.Context, trackToken string, requestedFormats []string) (*mediaResult, error) {
if strings.TrimSpace(c.license) == "" {
c.stateMu.Lock()
license := c.license
c.stateMu.Unlock()
if strings.TrimSpace(license) == "" {
return nil, errors.New("missing deezer license token")
}
if err := c.limiter.Wait(ctx); err != nil {
@@ -1265,7 +1335,7 @@ func (c *Client) getMediaURLWithRequest(ctx context.Context, trackToken string,
)
}
reqBody := map[string]any{
"license_token": c.license,
"license_token": license,
"track_tokens": []string{trackToken},
"media": []map[string]any{{
"type": "FULL",
@@ -1285,7 +1355,7 @@ func (c *Client) getMediaURLWithRequest(ctx context.Context, trackToken string,
req.Header.Set("Accept-Charset", "UTF-8")
req.Header.Set("Content-Type", "text/plain; charset=UTF-8")
resp, err := c.http.Do(req)
resp, err := netutil.Do(c.http, req)
if err != nil {
return nil, err
}
+51 -30
View File
@@ -619,11 +619,6 @@ func (c *Client) getPlaylist(ctx context.Context, playlistID string) (map[string
return nil, fmt.Errorf("playlist/get failed: status=%d", status)
}
total, _ := intValue(resp["tracks_count"])
if total <= pageLimit {
return resp, nil
}
tracksObj, ok := mapValue(resp["tracks"])
if !ok {
return resp, nil
@@ -633,7 +628,15 @@ func (c *Client) getPlaylist(ctx context.Context, playlistID string) (map[string
return resp, nil
}
for offset := pageLimit; offset < total; offset += pageLimit {
total, _ := intValue(resp["tracks_count"])
if total <= pageLimit && len(items) < pageLimit {
return resp, nil
}
for offset := pageLimit; ; offset += pageLimit {
if total > 0 && offset >= total {
break
}
pageParams := url.Values{}
pageParams.Set("app_id", c.cfg.Session.Qobuz.AppID)
pageParams.Set("playlist_id", playlistID)
@@ -650,13 +653,16 @@ func (c *Client) getPlaylist(ctx context.Context, playlistID string) (map[string
}
pageTracks, ok := mapValue(pageResp["tracks"])
if !ok {
continue
break
}
pageItems, ok := pageTracks["items"].([]any)
if !ok {
continue
if !ok || len(pageItems) == 0 {
break
}
items = append(items, pageItems...)
if len(pageItems) < pageLimit {
break
}
}
tracksObj["items"] = items
@@ -681,11 +687,6 @@ func (c *Client) getLabel(ctx context.Context, labelID string) (map[string]any,
return nil, fmt.Errorf("label/get failed: status=%d", status)
}
total, _ := intValue(resp["albums_count"])
if total <= pageLimit {
return resp, nil
}
albumsObj, ok := mapValue(resp["albums"])
if !ok {
return resp, nil
@@ -695,7 +696,15 @@ func (c *Client) getLabel(ctx context.Context, labelID string) (map[string]any,
return resp, nil
}
for offset := pageLimit; offset < total; offset += pageLimit {
total, _ := intValue(resp["albums_count"])
if total <= pageLimit && len(items) < pageLimit {
return resp, nil
}
for offset := pageLimit; ; offset += pageLimit {
if total > 0 && offset >= total {
break
}
pageParams := url.Values{}
pageParams.Set("app_id", c.cfg.Session.Qobuz.AppID)
pageParams.Set("label_id", labelID)
@@ -712,13 +721,16 @@ func (c *Client) getLabel(ctx context.Context, labelID string) (map[string]any,
}
pageAlbums, ok := mapValue(pageResp["albums"])
if !ok {
continue
break
}
pageItems, ok := pageAlbums["items"].([]any)
if !ok {
continue
if !ok || len(pageItems) == 0 {
break
}
items = append(items, pageItems...)
if len(pageItems) < pageLimit {
break
}
}
albumsObj["items"] = items
@@ -870,7 +882,7 @@ func (c *Client) apiRequest(ctx context.Context, endpoint string, params url.Val
}
req.Header.Set("User-Agent", "streamrip-go/0.1")
resp, err := c.http.Do(req)
resp, err := netutil.Do(c.http, req)
if err != nil {
return nil, 0, err
}
@@ -904,7 +916,7 @@ func (c *Client) fetchAppIDAndSecrets(ctx context.Context) (string, []string, er
if err != nil {
return "", nil, err
}
loginResp, err := c.http.Do(loginReq)
loginResp, err := netutil.Do(c.http, loginReq)
if err != nil {
return "", nil, err
}
@@ -926,7 +938,7 @@ func (c *Client) fetchAppIDAndSecrets(ctx context.Context) (string, []string, er
if err != nil {
return "", nil, err
}
bundleResp, err := c.http.Do(bundleReq)
bundleResp, err := netutil.Do(c.http, bundleReq)
if err != nil {
return "", nil, err
}
@@ -1041,6 +1053,13 @@ func (c *Client) ensureMobileSession(ctx context.Context) error {
return nil
}
func (c *Client) mobileAPIBase() string {
if c.baseURL != "" {
return c.baseURL
}
return baseURL
}
func (c *Client) mobileLogin(ctx context.Context, username, password string) error {
ts := time.Now().Unix()
params := url.Values{}
@@ -1050,13 +1069,13 @@ func (c *Client) mobileLogin(ctx context.Context, username, password string) err
params.Set("request_ts", strconv.FormatInt(ts, 10))
params.Set("request_sig", mobileSignRequest(c.mobileAppSecret(), "oauth2/login", []kv{{"password", password}, {"username", username}}, ts))
reqURL := baseURL + "/oauth2/login?" + params.Encode()
reqURL := c.mobileAPIBase() + "/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)
resp, err := netutil.Do(c.http, req)
if err != nil {
return fmt.Errorf("mobile login request failed: %w", err)
}
@@ -1090,7 +1109,7 @@ func (c *Client) mobileStartSession(ctx context.Context) error {
params.Set("request_ts", strconv.FormatInt(ts, 10))
params.Set("request_sig", mobileSignRequest(c.mobileAppSecret(), "session/start", []kv{{"profile", mobileSessionProf}}, ts))
reqURL := baseURL + "/session/start?" + params.Encode()
reqURL := c.mobileAPIBase() + "/session/start?" + params.Encode()
form := url.Values{}
form.Set("profile", mobileSessionProf)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, reqURL, strings.NewReader(form.Encode()))
@@ -1099,7 +1118,7 @@ func (c *Client) mobileStartSession(ctx context.Context) error {
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
c.setMobileHeaders(req)
resp, err := c.http.Do(req)
resp, err := netutil.Do(c.http, req)
if err != nil {
return fmt.Errorf("mobile session request failed: %w", err)
}
@@ -1136,13 +1155,13 @@ func (c *Client) mobileGetFileURL(ctx context.Context, trackID string, formatID
params.Set("intent", "stream")
params.Set("request_ts", strconv.FormatInt(ts, 10))
params.Set("request_sig", mobileSignRequest(c.mobileAppSecret(), "file/url", []kv{{"format_id", strconv.Itoa(formatID)}, {"intent", "stream"}, {"track_id", trackID}}, ts))
reqURL := baseURL + "/file/url?" + params.Encode()
reqURL := c.mobileAPIBase() + "/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)
resp, err := netutil.Do(c.http, req)
if err != nil {
return nil, err
}
@@ -1171,7 +1190,7 @@ func (c *Client) mobileCopyURLToWriter(ctx context.Context, sourceURL string, ou
if client == nil {
client = c.http
}
resp, err := client.Do(req)
resp, err := netutil.Do(client, req)
if err != nil {
return err
}
@@ -1228,7 +1247,7 @@ func (c *Client) mobileDownloadSegment(ctx context.Context, sourceURL string) ([
return nil, err
}
c.setMobileHeaders(req)
resp, err := c.http.Do(req)
resp, err := netutil.Do(c.http, req)
if err != nil {
lastErr = err
time.Sleep(time.Duration(500*(attempt+1)) * time.Millisecond)
@@ -1303,6 +1322,8 @@ func sortKVs(s []kv) {
}
func (c *Client) mobileDeriveTrackKey(encryptedKey string) ([]byte, error) {
c.mobileMu.Lock()
defer c.mobileMu.Unlock()
if len(c.mobileKEK) == 16 {
return unwrapQobuzTrackKey(encryptedKey, c.mobileKEK)
}
@@ -1599,7 +1620,7 @@ func (c *Client) fetchLyricsDocument(ctx context.Context, trackID, docURL string
if err != nil {
return "", "", err
}
resp, err := c.http.Do(req)
resp, err := netutil.Do(c.http, req)
if err != nil {
return "", "", err
}
+41 -5
View File
@@ -96,7 +96,7 @@ func (c *Client) Search(ctx context.Context, mediaType, query string, limit int)
func (c *Client) searchTracks(ctx context.Context, query string, limit int) ([]map[string]any, error) {
target := fmt.Sprintf("scsearch%d:%s", limit, query)
b, err := c.run(ctx, c.bin, "-J", "--flat-playlist", "--skip-download", "--no-warnings", target)
b, err := c.runYtdlp(ctx, "-J", "--flat-playlist", "--skip-download", "--no-warnings", target)
if err != nil {
return nil, err
}
@@ -154,7 +154,7 @@ func (c *Client) searchPlaylists(ctx context.Context, query string, limit int) (
return nil, err
}
}
resp, err := c.http.Do(req)
resp, err := netutil.Do(c.http, req)
if err != nil {
return nil, err
}
@@ -346,7 +346,7 @@ func (c *Client) trackInfo(ctx context.Context, item string) (map[string]any, er
}
c.mu.Unlock()
b, err := c.run(ctx, c.bin, "-J", "--no-playlist", "--skip-download", "--no-warnings", item)
b, err := c.runYtdlp(ctx, "-J", "--no-playlist", "--skip-download", "--no-warnings", item)
if err != nil {
return nil, err
}
@@ -367,7 +367,7 @@ func (c *Client) trackInfo(ctx context.Context, item string) (map[string]any, er
}
func (c *Client) playlistInfo(ctx context.Context, item string) (map[string]any, error) {
b, err := c.run(ctx, c.bin, "-J", "--flat-playlist", "--skip-download", "--no-warnings", item)
b, err := c.runYtdlp(ctx, "-J", "--flat-playlist", "--skip-download", "--no-warnings", item)
if err != nil {
return nil, err
}
@@ -503,11 +503,29 @@ func parseJSONMap(b []byte) (map[string]any, error) {
func cloneMap(in map[string]any) map[string]any {
out := make(map[string]any, len(in))
for k, v := range in {
out[k] = v
out[k] = cloneValue(v)
}
return out
}
// cloneValue deep-copies the container types JSON decoding produces. A shallow
// clone left nested maps and slices shared with the cache, so a caller that
// edited track metadata also rewrote what later calls received.
func cloneValue(v any) any {
switch t := v.(type) {
case map[string]any:
return cloneMap(t)
case []any:
out := make([]any, len(t))
for i, item := range t {
out[i] = cloneValue(item)
}
return out
default:
return v
}
}
func asAnySlice(v any) []any {
items, ok := v.([]any)
if !ok {
@@ -533,6 +551,24 @@ func soundcloudImageMap(raw string) map[string]any {
}
}
// ytdlpTimeout bounds each yt-dlp invocation. yt-dlp has no request timeout of
// its own: a stalled network read or a hung extractor would otherwise block a
// download worker forever, and Ctrl-C was the only way out.
const ytdlpTimeout = 5 * time.Minute
// runYtdlp applies the shared request limiter and a deadline before invoking
// yt-dlp, so external tool calls obey the same rate limits as HTTP requests.
func (c *Client) runYtdlp(ctx context.Context, args ...string) ([]byte, error) {
if c.limiter != nil {
if err := c.limiter.Wait(ctx); err != nil {
return nil, err
}
}
runCtx, cancel := context.WithTimeout(ctx, ytdlpTimeout)
defer cancel()
return c.run(runCtx, c.bin, args...)
}
func runCommand(ctx context.Context, name string, args ...string) ([]byte, error) {
cmd := exec.CommandContext(ctx, name, args...)
b, err := cmd.CombinedOutput()
+28 -6
View File
@@ -97,7 +97,13 @@ func (c *Client) Login(ctx context.Context) error {
if c.tokenNeedsRefresh() {
if err := c.refreshAccessToken(ctx); err != nil {
return err
// The token is close to expiry but may still work. Don't hard-fail
// a usable session just because the refresh endpoint is down; the
// sessions call below will reject it if it is really expired.
if c.tokenExpired() {
return err
}
verbose.Printf(verbose.V, "tidal: proactive token refresh failed; trying existing token: %v\n", err)
}
}
@@ -137,6 +143,14 @@ func (c *Client) tokenNeedsRefresh() bool {
return time.Until(time.Unix(expiry, 0)) < 24*time.Hour
}
func (c *Client) tokenExpired() bool {
expiry := c.cfg.Session.Tidal.TokenExpiry
if expiry <= 0 {
return false
}
return time.Now().After(time.Unix(expiry, 0))
}
func (c *Client) refreshAccessToken(ctx context.Context) error {
refresh := strings.TrimSpace(c.cfg.Session.Tidal.RefreshToken)
if refresh == "" {
@@ -301,13 +315,17 @@ func (c *Client) GetDownloadable(ctx context.Context, trackID string, quality in
quality = c.cfg.Session.Tidal.Quality
}
var atmosErr error
if c.cfg.Session.Tidal.PreferAtmos {
// 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 {
// through the format-specific trackManifests paths. Keep its error so
// a failed atmos attempt is visible if the normal path fails too.
d, err := c.getAtmosDownloadable(ctx, trackID)
if d != nil {
return d, nil
}
atmosErr = err
}
params := url.Values{}
@@ -334,7 +352,11 @@ func (c *Client) GetDownloadable(ctx context.Context, trackID string, quality in
}
}
return c.getDownloadableFromTrackManifest(ctx, trackID, quality)
d, err := c.getDownloadableFromTrackManifest(ctx, trackID, quality)
if err != nil && atmosErr != nil {
return nil, fmt.Errorf("tidal download failed: %v (atmos attempt: %w)", err, atmosErr)
}
return d, err
}
func (c *Client) getAtmosDownloadable(ctx context.Context, trackID string) (*provider.Downloadable, error) {
@@ -633,7 +655,7 @@ func (c *Client) GetVideoDownloadable(ctx context.Context, videoID string) (*pro
return nil, err
}
req.Header.Set("User-Agent", "streamrip-go/0.1")
respHTTP, err := c.http.Do(req)
respHTTP, err := netutil.Do(c.http, req)
if err != nil {
return nil, err
}
@@ -901,7 +923,7 @@ func (c *Client) doJSONWithRetry(ctx context.Context, newRequest func() (*http.R
if err != nil {
return nil, 0, err
}
resp, err := c.http.Do(req)
resp, err := netutil.Do(c.http, req)
if err != nil {
if attempt+1 < tidalRequestAttempts {
if waitErr := waitRetry(ctx, retryDelay("", attempt)); waitErr != nil {
+64 -19
View File
@@ -47,6 +47,9 @@ type Client struct {
// workers can reach concurrently.
authMu sync.Mutex
loggedIn bool
// userIDMu guards userID separately from authMu: addHeaders runs inside
// Login (which holds authMu) and from concurrent workers.
userIDMu sync.Mutex
userID string
}
@@ -85,7 +88,7 @@ func (c *Client) Login(ctx context.Context) error {
}
result, _ := resp["result"].(map[string]any)
if uid := strings.TrimSpace(jsonutil.StringFromAny(result["uid"])); uid != "" {
c.userID = uid
c.setUserID(uid)
if err := c.cfg.UpdateTokens(func(file, session *config.ConfigData) {
file.Yandex.UserID = uid
session.Yandex.UserID = uid
@@ -126,19 +129,40 @@ func (c *Client) Search(ctx context.Context, mediaType, query string, limit int)
if mediaType == "video" || mediaType == "label" {
return nil, fmt.Errorf("unsupported yandex search media type %q", mediaType)
}
params := url.Values{}
params.Set("text", query)
params.Set("type", searchType)
params.Set("page", "0")
resp, status, err := c.apiRequest(ctx, http.MethodGet, "/search", params, nil)
if err != nil {
return nil, err
items := make([]any, 0, limit)
total := -1
perPage := 0
for page := 0; len(items) < limit; page++ {
params := url.Values{}
params.Set("text", query)
params.Set("type", searchType)
params.Set("page", strconv.Itoa(page))
resp, status, err := c.apiRequest(ctx, http.MethodGet, "/search", params, nil)
if err != nil {
return nil, err
}
if status != http.StatusOK {
return nil, fmt.Errorf("yandex search failed: status=%d body=%v", status, resp)
}
result, _ := resp["result"].(map[string]any)
if page == 0 {
if bucket, ok := result[searchType+"s"].(map[string]any); ok {
total = jsonutil.IntFromAny(bucket["total"])
perPage = jsonutil.IntFromAny(bucket["perPage"])
}
}
pageItems := c.normalizeSearchItems(mediaType, result)
if len(pageItems) == 0 {
break
}
items = append(items, pageItems...)
if total > 0 && len(items) >= total {
break
}
if perPage > 0 && len(pageItems) < perPage {
break
}
}
if status != http.StatusOK {
return nil, fmt.Errorf("yandex search failed: status=%d body=%v", status, resp)
}
result, _ := resp["result"].(map[string]any)
items := c.normalizeSearchItems(mediaType, result)
if limit < len(items) {
items = items[:limit]
}
@@ -153,15 +177,20 @@ func (c *Client) GetDownloadable(ctx context.Context, item string, quality int)
if trackID == "" {
return nil, errors.New("empty yandex track id")
}
var encrawErr, rawErr error
if dl, err := c.getDesktopDownloadable(ctx, trackID, quality, "encraw"); err == nil {
dl.Source = "yandex"
dl.TrackID = trackID
return dl, nil
} else {
encrawErr = err
}
if dl, err := c.getDesktopDownloadable(ctx, trackID, quality, "raw"); err == nil {
dl.Source = "yandex"
dl.TrackID = trackID
return dl, nil
} else {
rawErr = err
}
legacy, legacyErr := c.getLegacyDownloadable(ctx, trackID)
if legacyErr == nil {
@@ -169,7 +198,7 @@ func (c *Client) GetDownloadable(ctx context.Context, item string, quality int)
legacy.TrackID = trackID
return legacy, nil
}
return nil, legacyErr
return nil, fmt.Errorf("yandex download failed: encraw: %v; raw: %v; legacy: %w", encrawErr, rawErr, legacyErr)
}
func (c *Client) Close() error {
@@ -410,8 +439,12 @@ func (c *Client) fetchLegacyXML(ctx context.Context, xmlURL string) (*legacyDown
if err != nil {
return nil, err
}
c.addHeaders(req)
resp, err := c.http.Do(req)
// xmlURL is supplied by the API response, not by us. Never call
// c.addHeaders here: it attaches the OAuth token and user id, which
// would hand both to whatever host the response names.
req.Header.Set("Accept", "*/*")
req.Header.Set("User-Agent", "streamrip-go/0.1")
resp, err := netutil.Do(c.http, req)
if err != nil {
return nil, err
}
@@ -507,7 +540,7 @@ func (c *Client) doRequestOnce(ctx context.Context, method, path string, params
if method == http.MethodPost && form != nil {
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
}
resp, err := c.http.Do(req)
resp, err := netutil.Do(c.http, req)
if err != nil {
return nil, 0, err
}
@@ -543,11 +576,23 @@ func (c *Client) addHeaders(req *http.Request) {
if strings.TrimSpace(c.cfg.Session.Yandex.AccessToken) != "" {
req.Header.Set("Authorization", "OAuth "+strings.TrimSpace(c.cfg.Session.Yandex.AccessToken))
}
if strings.TrimSpace(c.userID) != "" {
req.Header.Set("X-Yandex-Puid", strings.TrimSpace(c.userID))
if uid := c.currentUserID(); uid != "" {
req.Header.Set("X-Yandex-Puid", uid)
}
}
func (c *Client) setUserID(uid string) {
c.userIDMu.Lock()
c.userID = strings.TrimSpace(uid)
c.userIDMu.Unlock()
}
func (c *Client) currentUserID() string {
c.userIDMu.Lock()
defer c.userIDMu.Unlock()
return strings.TrimSpace(c.userID)
}
func mapResultSlice(resp map[string]any) []map[string]any {
result, ok := resp["result"].([]any)
if !ok {
+35 -9
View File
@@ -46,10 +46,10 @@ func NewSQLite(path string) (*SQLite, error) {
// sqliteDSN builds a file: URI with the pragmas this app needs.
//
// WAL lets a concurrent reader (for example `rip db browse`) run while a rip
// is writing, and busy_timeout makes a contended write wait instead of failing
// immediately with SQLITE_BUSY. The path is passed through url.URL so that a
// config path containing '?' or '#' is not parsed as query parameters.
// WAL lets a concurrent reader (for example `rip database browse`) run while a
// rip is writing, and busy_timeout makes a contended write wait instead of
// failing immediately with SQLITE_BUSY. The path is passed through url.URL so
// that a config path containing '?' or '#' is not parsed as query parameters.
func sqliteDSN(path string) string {
u := url.URL{Scheme: "file", Opaque: (&url.URL{Path: path}).EscapedPath()}
q := url.Values{}
@@ -282,22 +282,48 @@ func (s *SQLite) MarkDownloaded(ctx context.Context, source, id string) error {
s.mu.Lock()
defer s.mu.Unlock()
_, err := s.db.ExecContext(ctx, `INSERT OR IGNORE INTO downloads(source, id) VALUES (?, ?)`, source, id)
return err
// Recording the success and clearing an earlier failure must be atomic:
// otherwise a crash between the two leaves the item both downloaded and
// queued for retry, or a later retry overwrites a good file.
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer func() { _ = tx.Rollback() }()
if _, err = tx.ExecContext(ctx, `INSERT OR IGNORE INTO downloads(source, id) VALUES (?, ?)`, source, id); err != nil {
return err
}
if _, err = tx.ExecContext(ctx, `DELETE FROM failed_downloads WHERE source = ? AND id = ?`, source, id); err != nil {
return err
}
return tx.Commit()
}
func (s *SQLite) MarkFailed(ctx context.Context, source, mediaType, id string) error {
s.mu.Lock()
defer s.mu.Unlock()
_, err := s.db.ExecContext(
// A failed attempt supersedes an earlier success: --force truncates the
// existing file before downloading, so leaving the downloads row would
// make later runs skip a track whose audio is gone.
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer func() { _ = tx.Rollback() }()
if _, err = tx.ExecContext(
ctx,
`INSERT OR IGNORE INTO failed_downloads(source, media_type, id) VALUES (?, ?, ?)`,
source,
mediaType,
id,
)
return err
); err != nil {
return err
}
if _, err = tx.ExecContext(ctx, `DELETE FROM downloads WHERE source = ? AND id = ?`, source, id); err != nil {
return err
}
return tx.Commit()
}
// IsFailed reports whether a previous attempt at this item was recorded as
+35
View File
@@ -9,6 +9,41 @@ type Database interface {
Close() error
}
// FeatureFlags gates each database-backed feature independently. The config
// has separate downloads_enabled and failed_downloads_enabled switches, but a
// single SQLite file holds both tables; without this wrapper, enabling either
// switch silently enabled both.
type FeatureFlags struct {
DB Database
DownloadsEnabled bool
FailedEnabled bool
}
func (f *FeatureFlags) IsDownloaded(ctx context.Context, source, id string) (bool, error) {
if !f.DownloadsEnabled {
return false, nil
}
return f.DB.IsDownloaded(ctx, source, id)
}
func (f *FeatureFlags) MarkDownloaded(ctx context.Context, source, id string) error {
if !f.DownloadsEnabled {
return nil
}
return f.DB.MarkDownloaded(ctx, source, id)
}
func (f *FeatureFlags) MarkFailed(ctx context.Context, source, mediaType, id string) error {
if !f.FailedEnabled {
return nil
}
return f.DB.MarkFailed(ctx, source, mediaType, id)
}
func (f *FeatureFlags) Close() error {
return f.DB.Close()
}
type Dummy struct{}
func NewDummy() *Dummy {
+25 -1
View File
@@ -224,7 +224,19 @@ func parseDeezer(raw string, parts []string) *ParsedURL {
if !isSupportedMedia(mediaType) {
return nil
}
id := parts[1]
// Deezer share URLs can carry a slug before the numeric id
// (/album/some-title/123456). Prefer the last numeric segment instead of
// treating the slug as the id.
id := ""
for i := len(parts) - 1; i >= 1; i-- {
if isNumericSegment(parts[i]) {
id = parts[i]
break
}
}
if id == "" {
id = parts[1]
}
if id == "" {
return nil
}
@@ -232,6 +244,18 @@ func parseDeezer(raw string, parts []string) *ParsedURL {
return &ParsedURL{OriginalURL: raw, Source: "deezer", MediaType: mediaType, ID: id, Kind: KindGeneric}
}
func isNumericSegment(s string) bool {
if s == "" {
return false
}
for _, r := range s {
if r < '0' || r > '9' {
return false
}
}
return true
}
func parseSoundcloud(raw, host string, parts []string) *ParsedURL {
if len(parts) < 1 {
return nil