mirror of
https://git.sr.ht/~joren/streamrip-go
synced 2026-08-24 18:48:21 +02:00
Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8590a5b6b6
|
||
|
|
eb7854bac3
|
||
|
|
5f61b1a3cf
|
||
|
|
e336bb96f1
|
||
|
|
99c531928e
|
||
|
|
150b5b5d85
|
||
|
|
80bfbe0ecb
|
||
|
|
3413de1daa
|
@@ -25,6 +25,7 @@ type globalOptions struct {
|
|||||||
noProgress bool
|
noProgress bool
|
||||||
noSSLVerify bool
|
noSSLVerify bool
|
||||||
verbose int
|
verbose int
|
||||||
|
help bool
|
||||||
command string
|
command string
|
||||||
commandArgs []string
|
commandArgs []string
|
||||||
}
|
}
|
||||||
@@ -45,6 +46,9 @@ func parseGlobalArgs(args []string) (globalOptions, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
switch {
|
switch {
|
||||||
|
case isHelpArg(arg):
|
||||||
|
opts.help = true
|
||||||
|
return opts, nil
|
||||||
case arg == "-ndb" || arg == "--no-db":
|
case arg == "-ndb" || arg == "--no-db":
|
||||||
opts.noDB = true
|
opts.noDB = true
|
||||||
case arg == "--no-progress":
|
case arg == "--no-progress":
|
||||||
|
|||||||
+160
@@ -0,0 +1,160 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
func isHelpArg(arg string) bool {
|
||||||
|
return arg == "-h" || arg == "--help"
|
||||||
|
}
|
||||||
|
|
||||||
|
func commandWantsHelp(args []string) bool {
|
||||||
|
for _, arg := range args {
|
||||||
|
if isHelpArg(arg) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func printMainHelp(w io.Writer) {
|
||||||
|
fmt.Fprint(w, `streamrip-go
|
||||||
|
|
||||||
|
Usage:
|
||||||
|
rip [global options] <command> [command options]
|
||||||
|
rip help [command]
|
||||||
|
|
||||||
|
Commands:
|
||||||
|
url Rip one or more URLs
|
||||||
|
file Rip URLs or IDs from a file
|
||||||
|
id Rip by source, media type, and ID
|
||||||
|
search Search a provider and download selected results
|
||||||
|
lastfm Import a Last.fm playlist
|
||||||
|
config Manage configuration
|
||||||
|
database Inspect download databases
|
||||||
|
|
||||||
|
Global options:
|
||||||
|
-f, --folder <path> Override downloads folder
|
||||||
|
-q, --quality <0-4> Override provider quality
|
||||||
|
-c, --codec <codec> Convert after download: ALAC, FLAC, OGG, MP3, AAC
|
||||||
|
-ndb, --no-db Ignore download database
|
||||||
|
--no-progress Disable progress bars
|
||||||
|
--no-ssl-verify Disable TLS verification
|
||||||
|
--config-path <path> Use a custom config file
|
||||||
|
-v, -vv Verbose logging
|
||||||
|
-h, --help Show help
|
||||||
|
|
||||||
|
Run 'rip help <command>' for command-specific help.
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
func printCommandHelp(w io.Writer, command string) bool {
|
||||||
|
switch strings.ToLower(strings.TrimSpace(command)) {
|
||||||
|
case "url":
|
||||||
|
fmt.Fprint(w, `Usage:
|
||||||
|
rip url <url...> [--force|--ignore-db]
|
||||||
|
|
||||||
|
Rip one or more provider URLs.
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
rip url https://www.beatport.com/release/example/123
|
||||||
|
rip url https://play.qobuz.com/album/abc --force
|
||||||
|
|
||||||
|
Options:
|
||||||
|
--force, --ignore-db Redownload even if already in the database
|
||||||
|
`)
|
||||||
|
case "file":
|
||||||
|
fmt.Fprint(w, `Usage:
|
||||||
|
rip file <path> [--force|--ignore-db]
|
||||||
|
|
||||||
|
Rip URLs or JSON ID entries from a file.
|
||||||
|
|
||||||
|
Options:
|
||||||
|
--force, --ignore-db Redownload even if already in the database
|
||||||
|
`)
|
||||||
|
case "id":
|
||||||
|
fmt.Fprint(w, `Usage:
|
||||||
|
rip id <source> <media-type> <id> [quality] [--force|--ignore-db]
|
||||||
|
|
||||||
|
Rip an item by provider ID.
|
||||||
|
|
||||||
|
Sources:
|
||||||
|
qobuz, tidal, deezer, yandex, beatport, soundcloud
|
||||||
|
|
||||||
|
Media types:
|
||||||
|
track, album, playlist, artist, label, chart, video
|
||||||
|
|
||||||
|
Options:
|
||||||
|
quality Override quality for this rip, 0-4
|
||||||
|
--force, --ignore-db Redownload even if already in the database
|
||||||
|
`)
|
||||||
|
case "search":
|
||||||
|
fmt.Fprint(w, `Usage:
|
||||||
|
rip search <source> <media-type> <query...> [options]
|
||||||
|
|
||||||
|
Search a provider and optionally download selected results.
|
||||||
|
|
||||||
|
Sources:
|
||||||
|
qobuz, tidal, deezer, yandex, beatport, soundcloud
|
||||||
|
|
||||||
|
Media types:
|
||||||
|
track, album, playlist, artist, label, chart, video
|
||||||
|
|
||||||
|
Options:
|
||||||
|
--limit N Maximum results to show
|
||||||
|
--first Download the first result without prompting
|
||||||
|
--no-download Show results only
|
||||||
|
--output-file <path> Write results as JSON
|
||||||
|
--force, --ignore-db Redownload even if already in the database
|
||||||
|
`)
|
||||||
|
case "lastfm":
|
||||||
|
fmt.Fprint(w, `Usage:
|
||||||
|
rip lastfm [--source SOURCE] [--fallback-source SOURCE] <playlist_url>
|
||||||
|
|
||||||
|
Import a Last.fm playlist and resolve tracks through configured providers.
|
||||||
|
|
||||||
|
Options:
|
||||||
|
--source SOURCE Primary lookup source
|
||||||
|
--fallback-source SOURCE Fallback lookup source
|
||||||
|
`)
|
||||||
|
case "config":
|
||||||
|
fmt.Fprint(w, `Usage:
|
||||||
|
rip config <open|reset|path> [options]
|
||||||
|
|
||||||
|
Manage configuration.
|
||||||
|
|
||||||
|
Commands:
|
||||||
|
open Open the config file in an editor
|
||||||
|
reset Reset config to defaults
|
||||||
|
path Print the config path
|
||||||
|
|
||||||
|
Options:
|
||||||
|
-v, --vim Use Vim for 'rip config open'
|
||||||
|
-y, --yes Confirm 'rip config reset' without prompting
|
||||||
|
`)
|
||||||
|
case "database":
|
||||||
|
fmt.Fprint(w, `Usage:
|
||||||
|
rip database browse <downloads|failed>
|
||||||
|
|
||||||
|
Inspect local download databases.
|
||||||
|
`)
|
||||||
|
case "dev-help":
|
||||||
|
printDeveloperHelp(w)
|
||||||
|
default:
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func printDeveloperHelp(w io.Writer) {
|
||||||
|
fmt.Fprint(w, `Developer smoke commands:
|
||||||
|
soundcloud-smoke
|
||||||
|
qobuz-smoke, qobuz-rip-smoke, qobuz-convert-rip-smoke
|
||||||
|
qobuz-album-rip-smoke, qobuz-playlist-rip-smoke, qobuz-artist-rip-smoke, qobuz-label-rip-smoke
|
||||||
|
qobuz-search-smoke
|
||||||
|
tidal-search-smoke, tidal-metadata-smoke, tidal-video-smoke
|
||||||
|
tidal-rip-smoke, tidal-album-rip-smoke, tidal-playlist-rip-smoke, tidal-artist-rip-smoke
|
||||||
|
`)
|
||||||
|
}
|
||||||
+35
-17
@@ -25,10 +25,34 @@ func main() {
|
|||||||
fmt.Fprintf(os.Stderr, "option error: %v\n", err)
|
fmt.Fprintf(os.Stderr, "option error: %v\n", err)
|
||||||
os.Exit(2)
|
os.Exit(2)
|
||||||
}
|
}
|
||||||
|
if gopts.help {
|
||||||
|
printMainHelp(os.Stdout)
|
||||||
|
return
|
||||||
|
}
|
||||||
if gopts.command == "" {
|
if gopts.command == "" {
|
||||||
fmt.Println("usage: rip <command>")
|
printMainHelp(os.Stdout)
|
||||||
fmt.Println("commands: url, file, config, database, id, search, lastfm")
|
os.Exit(2)
|
||||||
fmt.Println("tip: run `rip dev-help` to list developer smoke commands")
|
}
|
||||||
|
if gopts.command == "help" {
|
||||||
|
if len(gopts.commandArgs) == 0 || isHelpArg(gopts.commandArgs[0]) {
|
||||||
|
printMainHelp(os.Stdout)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if printCommandHelp(os.Stdout, gopts.commandArgs[0]) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
fmt.Fprintf(os.Stderr, "unknown help topic: %s\n", gopts.commandArgs[0])
|
||||||
|
os.Exit(2)
|
||||||
|
}
|
||||||
|
if gopts.command == "dev-help" {
|
||||||
|
printDeveloperHelp(os.Stdout)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if commandWantsHelp(gopts.commandArgs) {
|
||||||
|
if printCommandHelp(os.Stdout, gopts.command) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
fmt.Fprintf(os.Stderr, "unknown command: %s\n", gopts.command)
|
||||||
os.Exit(2)
|
os.Exit(2)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -64,17 +88,11 @@ func main() {
|
|||||||
|
|
||||||
switch os.Args[1] {
|
switch os.Args[1] {
|
||||||
case "dev-help":
|
case "dev-help":
|
||||||
fmt.Println("developer smoke commands:")
|
printDeveloperHelp(os.Stdout)
|
||||||
fmt.Println(" soundcloud-smoke")
|
|
||||||
fmt.Println(" qobuz-smoke, qobuz-rip-smoke, qobuz-convert-rip-smoke")
|
|
||||||
fmt.Println(" qobuz-album-rip-smoke, qobuz-playlist-rip-smoke, qobuz-artist-rip-smoke, qobuz-label-rip-smoke")
|
|
||||||
fmt.Println(" qobuz-search-smoke")
|
|
||||||
fmt.Println(" tidal-search-smoke, tidal-metadata-smoke, tidal-video-smoke")
|
|
||||||
fmt.Println(" tidal-rip-smoke, tidal-album-rip-smoke, tidal-playlist-rip-smoke, tidal-artist-rip-smoke")
|
|
||||||
return
|
return
|
||||||
case "url":
|
case "url":
|
||||||
if len(os.Args) < 3 {
|
if len(os.Args) < 3 {
|
||||||
fmt.Println("usage: rip url <url...> [--force|--ignore-db]")
|
printCommandHelp(os.Stdout, "url")
|
||||||
os.Exit(2)
|
os.Exit(2)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -119,7 +137,7 @@ func main() {
|
|||||||
fmt.Printf("url rip complete (%d item(s))\n", added)
|
fmt.Printf("url rip complete (%d item(s))\n", added)
|
||||||
case "file":
|
case "file":
|
||||||
if len(os.Args) < 3 {
|
if len(os.Args) < 3 {
|
||||||
fmt.Println("usage: rip file <path> [--force|--ignore-db]")
|
printCommandHelp(os.Stdout, "file")
|
||||||
os.Exit(2)
|
os.Exit(2)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -192,7 +210,7 @@ func main() {
|
|||||||
fmt.Printf("file rip complete (%d item(s))\n", added)
|
fmt.Printf("file rip complete (%d item(s))\n", added)
|
||||||
case "config":
|
case "config":
|
||||||
if len(os.Args) < 3 {
|
if len(os.Args) < 3 {
|
||||||
fmt.Println("usage: rip config <open|reset|path> [options]")
|
printCommandHelp(os.Stdout, "config")
|
||||||
os.Exit(2)
|
os.Exit(2)
|
||||||
}
|
}
|
||||||
switch os.Args[2] {
|
switch os.Args[2] {
|
||||||
@@ -258,7 +276,7 @@ func main() {
|
|||||||
}
|
}
|
||||||
case "database":
|
case "database":
|
||||||
if len(os.Args) < 4 || os.Args[2] != "browse" {
|
if len(os.Args) < 4 || os.Args[2] != "browse" {
|
||||||
fmt.Println("usage: rip database browse <downloads|failed>")
|
printCommandHelp(os.Stdout, "database")
|
||||||
os.Exit(2)
|
os.Exit(2)
|
||||||
}
|
}
|
||||||
table := strings.ToLower(strings.TrimSpace(os.Args[3]))
|
table := strings.ToLower(strings.TrimSpace(os.Args[3]))
|
||||||
@@ -294,7 +312,7 @@ func main() {
|
|||||||
}
|
}
|
||||||
case "id":
|
case "id":
|
||||||
if len(os.Args) < 5 {
|
if len(os.Args) < 5 {
|
||||||
fmt.Println("usage: rip id <source> <track|album|playlist|artist|label|chart|video> <id> [quality] [--force|--ignore-db]")
|
printCommandHelp(os.Stdout, "id")
|
||||||
os.Exit(2)
|
os.Exit(2)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -354,7 +372,7 @@ func main() {
|
|||||||
var sopts searchOptions
|
var sopts searchOptions
|
||||||
if len(os.Args) < 5 {
|
if len(os.Args) < 5 {
|
||||||
if !term.IsTerminal(int(os.Stdin.Fd())) {
|
if !term.IsTerminal(int(os.Stdin.Fd())) {
|
||||||
fmt.Println("usage: rip search <qobuz|tidal|deezer|yandex|beatport|soundcloud> <track|album|playlist|artist|label|chart|video> <query...> [--limit N] [--force|--ignore-db] [--no-download]")
|
printCommandHelp(os.Stdout, "search")
|
||||||
os.Exit(2)
|
os.Exit(2)
|
||||||
}
|
}
|
||||||
source, mediaType, sopts, err = promptSearchInteractive(cfg.Session.CLI.MaxSearchResults)
|
source, mediaType, sopts, err = promptSearchInteractive(cfg.Session.CLI.MaxSearchResults)
|
||||||
@@ -549,7 +567,7 @@ func main() {
|
|||||||
opts, parseErr := parseLastFMArgs(os.Args[2:], cfg.Session.LastFM.Source, cfg.Session.LastFM.FallbackSource)
|
opts, parseErr := parseLastFMArgs(os.Args[2:], cfg.Session.LastFM.Source, cfg.Session.LastFM.FallbackSource)
|
||||||
if parseErr != nil {
|
if parseErr != nil {
|
||||||
fmt.Fprintf(os.Stderr, "lastfm option error: %v\n", parseErr)
|
fmt.Fprintf(os.Stderr, "lastfm option error: %v\n", parseErr)
|
||||||
fmt.Println("usage: rip lastfm [--source SOURCE] [--fallback-source SOURCE] <playlist_url>")
|
printCommandHelp(os.Stdout, "lastfm")
|
||||||
os.Exit(2)
|
os.Exit(2)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
"errors"
|
"errors"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
@@ -206,6 +207,58 @@ func TestParseGlobalArgsNoDBBeforeCommand(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestParseGlobalArgsHelp(t *testing.T) {
|
||||||
|
opts, err := parseGlobalArgs([]string{"--help"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("parseGlobalArgs() error = %v", err)
|
||||||
|
}
|
||||||
|
if !opts.help {
|
||||||
|
t.Fatalf("expected help=true")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCommandWantsHelp(t *testing.T) {
|
||||||
|
if !commandWantsHelp([]string{"https://example.com", "-h"}) {
|
||||||
|
t.Fatalf("expected command help")
|
||||||
|
}
|
||||||
|
if commandWantsHelp([]string{"https://example.com"}) {
|
||||||
|
t.Fatalf("did not expect command help")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMainHelpHidesDeveloperCommands(t *testing.T) {
|
||||||
|
var buf bytes.Buffer
|
||||||
|
printMainHelp(&buf)
|
||||||
|
out := buf.String()
|
||||||
|
if !strings.Contains(out, "rip help [command]") || !strings.Contains(out, "Commands:") {
|
||||||
|
t.Fatalf("main help missing expected text: %s", out)
|
||||||
|
}
|
||||||
|
if strings.Contains(out, "dev-help") || strings.Contains(out, "smoke") {
|
||||||
|
t.Fatalf("main help should hide developer commands: %s", out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCommandHelpURL(t *testing.T) {
|
||||||
|
var buf bytes.Buffer
|
||||||
|
if !printCommandHelp(&buf, "url") {
|
||||||
|
t.Fatalf("expected url help")
|
||||||
|
}
|
||||||
|
out := buf.String()
|
||||||
|
if !strings.Contains(out, "rip url <url...>") || !strings.Contains(out, "--ignore-db") {
|
||||||
|
t.Fatalf("url help missing expected text: %s", out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPrintCommandHelpRejectsUnknown(t *testing.T) {
|
||||||
|
var buf bytes.Buffer
|
||||||
|
if printCommandHelp(&buf, "nope") {
|
||||||
|
t.Fatalf("unexpected help for unknown command")
|
||||||
|
}
|
||||||
|
if buf.Len() != 0 {
|
||||||
|
t.Fatalf("unexpected output for unknown command: %s", buf.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestParseGlobalArgsAllOfficialFlags(t *testing.T) {
|
func TestParseGlobalArgsAllOfficialFlags(t *testing.T) {
|
||||||
opts, err := parseGlobalArgs([]string{
|
opts, err := parseGlobalArgs([]string{
|
||||||
"--config-path", "/tmp/custom.toml",
|
"--config-path", "/tmp/custom.toml",
|
||||||
|
|||||||
+113
-14
@@ -11,6 +11,7 @@ import (
|
|||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
"streamrip-go/internal/artwork"
|
"streamrip-go/internal/artwork"
|
||||||
"streamrip-go/internal/audio/convert"
|
"streamrip-go/internal/audio/convert"
|
||||||
@@ -58,6 +59,7 @@ type ripTrackOptions struct {
|
|||||||
forPlaylist bool
|
forPlaylist bool
|
||||||
playlistName string
|
playlistName string
|
||||||
playlistPos int
|
playlistPos int
|
||||||
|
playlistYear int
|
||||||
}
|
}
|
||||||
|
|
||||||
type folderAudioValues struct {
|
type folderAudioValues struct {
|
||||||
@@ -372,14 +374,22 @@ func (m *Main) ripTrackCollection(ctx context.Context, p provider.Client, source
|
|||||||
ids = append(ids, id)
|
ids = append(ids, id)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
var artRes artwork.Result
|
||||||
|
var playlistYear int
|
||||||
|
if playlistLike {
|
||||||
|
artRes, _ = artwork.Prepare(ctx, m.DL, folder, meta, m.Config.Session.Artwork, true)
|
||||||
|
playlistYear = extractYear(meta)
|
||||||
|
}
|
||||||
|
|
||||||
m.logf("%s: %s (%d tracks)\n", kind, name, len(ids))
|
m.logf("%s: %s (%d tracks)\n", kind, name, len(ids))
|
||||||
failures := 0
|
failures := 0
|
||||||
runOne := func(i int, trackID string) {
|
runOne := func(i int, trackID string) {
|
||||||
opts := ripTrackOptions{albumFolder: folder, index: i, total: len(ids)}
|
opts := ripTrackOptions{albumFolder: folder, albumEmbedCover: artRes.EmbedPath, index: i, total: len(ids)}
|
||||||
if playlistLike {
|
if playlistLike {
|
||||||
opts.forPlaylist = true
|
opts.forPlaylist = true
|
||||||
opts.playlistName = name
|
opts.playlistName = name
|
||||||
opts.playlistPos = i
|
opts.playlistPos = i
|
||||||
|
opts.playlistYear = playlistYear
|
||||||
}
|
}
|
||||||
if err := m.ripTrack(ctx, p, source, trackID, "", opts); err != nil {
|
if err := m.ripTrack(ctx, p, source, trackID, "", opts); err != nil {
|
||||||
failures++
|
failures++
|
||||||
@@ -404,11 +414,12 @@ func (m *Main) ripTrackCollection(ctx context.Context, p provider.Client, source
|
|||||||
go func(pos int, tid string) {
|
go func(pos int, tid string) {
|
||||||
defer wg.Done()
|
defer wg.Done()
|
||||||
defer func() { <-sem }()
|
defer func() { <-sem }()
|
||||||
opts := ripTrackOptions{albumFolder: folder, index: pos, total: len(ids)}
|
opts := ripTrackOptions{albumFolder: folder, albumEmbedCover: artRes.EmbedPath, index: pos, total: len(ids)}
|
||||||
if playlistLike {
|
if playlistLike {
|
||||||
opts.forPlaylist = true
|
opts.forPlaylist = true
|
||||||
opts.playlistName = name
|
opts.playlistName = name
|
||||||
opts.playlistPos = pos
|
opts.playlistPos = pos
|
||||||
|
opts.playlistYear = playlistYear
|
||||||
}
|
}
|
||||||
if err := m.ripTrack(ctx, p, source, tid, "", opts); err != nil {
|
if err := m.ripTrack(ctx, p, source, tid, "", opts); err != nil {
|
||||||
mu.Lock()
|
mu.Lock()
|
||||||
@@ -648,10 +659,7 @@ func (m *Main) ripAlbum(ctx context.Context, p provider.Client, source, albumID
|
|||||||
}
|
}
|
||||||
|
|
||||||
albumTitle := titleFromMetadata(albumMeta, albumID)
|
albumTitle := titleFromMetadata(albumMeta, albumID)
|
||||||
albumArtist := jsonutil.NestedString(albumMeta, "artist", "name")
|
albumArtist := extractAlbumArtist(albumMeta)
|
||||||
if albumArtist == "" {
|
|
||||||
albumArtist = "Unknown"
|
|
||||||
}
|
|
||||||
releaseDate := jsonutil.StringFromAny(albumMeta["release_date_original"])
|
releaseDate := jsonutil.StringFromAny(albumMeta["release_date_original"])
|
||||||
if releaseDate == "" {
|
if releaseDate == "" {
|
||||||
releaseDate = jsonutil.StringFromAny(albumMeta["release_date"])
|
releaseDate = jsonutil.StringFromAny(albumMeta["release_date"])
|
||||||
@@ -809,6 +817,10 @@ func (m *Main) ripPlaylist(ctx context.Context, p provider.Client, source, playl
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
artRes, _ := artwork.Prepare(ctx, m.DL, folder, playlistMeta, m.Config.Session.Artwork, true)
|
||||||
|
|
||||||
|
playlistYear := extractYear(playlistMeta)
|
||||||
|
|
||||||
total := len(ids)
|
total := len(ids)
|
||||||
m.logf("Playlist: %s (%d tracks)\n", name, total)
|
m.logf("Playlist: %s (%d tracks)\n", name, total)
|
||||||
failures := 0
|
failures := 0
|
||||||
@@ -816,11 +828,13 @@ func (m *Main) ripPlaylist(ctx context.Context, p provider.Client, source, playl
|
|||||||
runOne := func(i int, id string) {
|
runOne := func(i int, id string) {
|
||||||
opts := ripTrackOptions{
|
opts := ripTrackOptions{
|
||||||
albumFolder: folder,
|
albumFolder: folder,
|
||||||
|
albumEmbedCover: artRes.EmbedPath,
|
||||||
index: i,
|
index: i,
|
||||||
total: total,
|
total: total,
|
||||||
forPlaylist: true,
|
forPlaylist: true,
|
||||||
playlistName: name,
|
playlistName: name,
|
||||||
playlistPos: i,
|
playlistPos: i,
|
||||||
|
playlistYear: playlistYear,
|
||||||
}
|
}
|
||||||
if err := m.ripTrack(ctx, p, source, id, "", opts); err != nil {
|
if err := m.ripTrack(ctx, p, source, id, "", opts); err != nil {
|
||||||
failures++
|
failures++
|
||||||
@@ -846,7 +860,7 @@ func (m *Main) ripPlaylist(ctx context.Context, p provider.Client, source, playl
|
|||||||
go func(pos int, tid string) {
|
go func(pos int, tid string) {
|
||||||
defer wg.Done()
|
defer wg.Done()
|
||||||
defer func() { <-sem }()
|
defer func() { <-sem }()
|
||||||
opts := ripTrackOptions{albumFolder: folder, index: pos, total: total, forPlaylist: true, playlistName: name, playlistPos: pos}
|
opts := ripTrackOptions{albumFolder: folder, albumEmbedCover: artRes.EmbedPath, index: pos, total: total, forPlaylist: true, playlistName: name, playlistPos: pos, playlistYear: playlistYear}
|
||||||
if err := m.ripTrack(ctx, p, source, tid, "", opts); err != nil {
|
if err := m.ripTrack(ctx, p, source, tid, "", opts); err != nil {
|
||||||
mu.Lock()
|
mu.Lock()
|
||||||
failures++
|
failures++
|
||||||
@@ -1013,7 +1027,7 @@ func (m *Main) ripTrack(ctx context.Context, p provider.Client, source, id, fall
|
|||||||
downloaded:
|
downloaded:
|
||||||
|
|
||||||
embedCoverPath := opts.albumEmbedCover
|
embedCoverPath := opts.albumEmbedCover
|
||||||
if opts.forPlaylist {
|
if opts.forPlaylist && embedCoverPath == "" {
|
||||||
parent := opts.albumFolder
|
parent := opts.albumFolder
|
||||||
if parent == "" {
|
if parent == "" {
|
||||||
parent = filepath.Dir(outPath)
|
parent = filepath.Dir(outPath)
|
||||||
@@ -1023,7 +1037,7 @@ downloaded:
|
|||||||
embedCoverPath = res.EmbedPath
|
embedCoverPath = res.EmbedPath
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else if embedCoverPath == "" {
|
} else if !opts.forPlaylist && embedCoverPath == "" {
|
||||||
parent := opts.albumFolder
|
parent := opts.albumFolder
|
||||||
if parent == "" {
|
if parent == "" {
|
||||||
parent = filepath.Dir(outPath)
|
parent = filepath.Dir(outPath)
|
||||||
@@ -1224,10 +1238,7 @@ func (m *Main) trackOutputPath(source, id, title, ext string, d *provider.Downlo
|
|||||||
if albumID == "" {
|
if albumID == "" {
|
||||||
albumID = id
|
albumID = id
|
||||||
}
|
}
|
||||||
albumArtist := jsonutil.NestedString(trackMeta, "album", "artist", "name")
|
albumArtist := extractAlbumArtist(trackMetaAlbum(trackMeta))
|
||||||
if albumArtist == "" {
|
|
||||||
albumArtist = jsonutil.NestedString(trackMeta, "performer", "name")
|
|
||||||
}
|
|
||||||
albumYear := naming.YearFromDate(jsonutil.StringFromAny(trackMeta["release_date_original"]))
|
albumYear := naming.YearFromDate(jsonutil.StringFromAny(trackMeta["release_date_original"]))
|
||||||
if albumYear == "Unknown" {
|
if albumYear == "Unknown" {
|
||||||
albumYear = naming.YearFromDate(jsonutil.StringFromAny(trackMeta["release_date"]))
|
albumYear = naming.YearFromDate(jsonutil.StringFromAny(trackMeta["release_date"]))
|
||||||
@@ -1310,7 +1321,7 @@ 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(jsonutil.StringFromAny(meta["version"]))
|
version := strings.TrimSpace(jsonutil.StringFromAny(meta["version"]))
|
||||||
if version != "" {
|
if version != "" && !isOriginalMix(version) {
|
||||||
return title + " (" + version + ")"
|
return title + " (" + version + ")"
|
||||||
}
|
}
|
||||||
if title != "" {
|
if title != "" {
|
||||||
@@ -1320,6 +1331,10 @@ func titleFromMetadata(meta map[string]any, fallback string) string {
|
|||||||
return fallback
|
return fallback
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func isOriginalMix(version string) bool {
|
||||||
|
return strings.EqualFold(strings.TrimSpace(version), "Original Mix")
|
||||||
|
}
|
||||||
|
|
||||||
func replaygainGainFromAny(v any) string {
|
func replaygainGainFromAny(v any) string {
|
||||||
s := strings.TrimSpace(jsonutil.StringFromAny(v))
|
s := strings.TrimSpace(jsonutil.StringFromAny(v))
|
||||||
if s == "" {
|
if s == "" {
|
||||||
@@ -1358,6 +1373,7 @@ func buildTagMetadata(trackMeta map[string]any, title, source, trackID string, o
|
|||||||
if artist == "" {
|
if artist == "" {
|
||||||
artist = jsonutil.NestedString(trackMeta, "artist", "name")
|
artist = jsonutil.NestedString(trackMeta, "artist", "name")
|
||||||
}
|
}
|
||||||
|
artistNames := stringSliceFromAny(trackMeta["artist_names"])
|
||||||
albumArtist := jsonutil.NestedString(trackMeta, "album", "artist", "name")
|
albumArtist := jsonutil.NestedString(trackMeta, "album", "artist", "name")
|
||||||
if albumArtist == "" {
|
if albumArtist == "" {
|
||||||
albumArtist = artist
|
albumArtist = artist
|
||||||
@@ -1394,6 +1410,9 @@ func buildTagMetadata(trackMeta map[string]any, title, source, trackID string, o
|
|||||||
if trackTotal == 0 {
|
if trackTotal == 0 {
|
||||||
trackTotal = jsonutil.IntFromAny(trackMeta["track_total"])
|
trackTotal = jsonutil.IntFromAny(trackMeta["track_total"])
|
||||||
}
|
}
|
||||||
|
if trackTotal == 0 && opts.total > 0 {
|
||||||
|
trackTotal = opts.total
|
||||||
|
}
|
||||||
if opts.forPlaylist && opts.total > 0 {
|
if opts.forPlaylist && opts.total > 0 {
|
||||||
trackTotal = opts.total
|
trackTotal = opts.total
|
||||||
}
|
}
|
||||||
@@ -1469,8 +1488,11 @@ func buildTagMetadata(trackMeta map[string]any, title, source, trackID string, o
|
|||||||
Title: title,
|
Title: title,
|
||||||
Album: album,
|
Album: album,
|
||||||
Artist: artist,
|
Artist: artist,
|
||||||
|
Artists: artistNames,
|
||||||
AlbumArtist: albumArtist,
|
AlbumArtist: albumArtist,
|
||||||
|
Compilation: opts.forPlaylist,
|
||||||
OmitDiscTags: opts.forPlaylist,
|
OmitDiscTags: opts.forPlaylist,
|
||||||
|
Year: opts.playlistYear,
|
||||||
TrackNumber: trackNumber,
|
TrackNumber: trackNumber,
|
||||||
DiscNumber: discNumber,
|
DiscNumber: discNumber,
|
||||||
TrackTotal: trackTotal,
|
TrackTotal: trackTotal,
|
||||||
@@ -1494,6 +1516,24 @@ func buildTagMetadata(trackMeta map[string]any, title, source, trackID string, o
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func stringSliceFromAny(v any) []string {
|
||||||
|
items, ok := v.([]string)
|
||||||
|
if ok {
|
||||||
|
return append([]string(nil), items...)
|
||||||
|
}
|
||||||
|
rawItems, ok := v.([]any)
|
||||||
|
if !ok {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
out := make([]string, 0, len(rawItems))
|
||||||
|
for _, raw := range rawItems {
|
||||||
|
if s := strings.TrimSpace(jsonutil.StringFromAny(raw)); s != "" {
|
||||||
|
out = append(out, s)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
func normalizeInitialKey(in string) string {
|
func normalizeInitialKey(in string) string {
|
||||||
s := strings.TrimSpace(in)
|
s := strings.TrimSpace(in)
|
||||||
if s == "" {
|
if s == "" {
|
||||||
@@ -1586,3 +1626,62 @@ func isFFmpegMissingError(err error) bool {
|
|||||||
}
|
}
|
||||||
return strings.Contains(strings.ToLower(err.Error()), "ffmpeg not found")
|
return strings.Contains(strings.ToLower(err.Error()), "ffmpeg not found")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func extractAlbumArtist(albumMeta map[string]any) string {
|
||||||
|
if artistsRaw, ok := albumMeta["artists"].([]any); ok {
|
||||||
|
names := make([]string, 0, len(artistsRaw))
|
||||||
|
for _, a := range artistsRaw {
|
||||||
|
artist, ok := a.(map[string]any)
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if name := jsonutil.StringFromAny(artist["name"]); name != "" {
|
||||||
|
names = append(names, name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(names) > 0 {
|
||||||
|
return displayArtistNames(names)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if names := stringSliceFromAny(albumMeta["artist_names"]); len(names) > 0 {
|
||||||
|
return displayArtistNames(names)
|
||||||
|
}
|
||||||
|
artist := jsonutil.NestedString(albumMeta, "artist", "name")
|
||||||
|
if artist != "" {
|
||||||
|
return artist
|
||||||
|
}
|
||||||
|
return "Unknown"
|
||||||
|
}
|
||||||
|
|
||||||
|
func displayArtistNames(names []string) string {
|
||||||
|
switch len(names) {
|
||||||
|
case 0:
|
||||||
|
return ""
|
||||||
|
case 1:
|
||||||
|
return names[0]
|
||||||
|
case 2:
|
||||||
|
return names[0] + " & " + names[1]
|
||||||
|
default:
|
||||||
|
return strings.Join(names[:len(names)-1], ", ") + " & " + names[len(names)-1]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func extractYear(meta map[string]any) int {
|
||||||
|
date := jsonutil.FirstNonEmpty(
|
||||||
|
jsonutil.StringFromAny(meta["publish_date"]),
|
||||||
|
jsonutil.StringFromAny(meta["creation_date"]),
|
||||||
|
jsonutil.StringFromAny(meta["created_at"]),
|
||||||
|
jsonutil.StringFromAny(meta["release_date"]),
|
||||||
|
jsonutil.StringFromAny(meta["new_release_date"]),
|
||||||
|
)
|
||||||
|
if date == "" {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
if t, err := time.Parse(time.RFC3339, date); err == nil {
|
||||||
|
return t.Year()
|
||||||
|
}
|
||||||
|
if t, err := time.Parse("2006-01-02", date); err == nil {
|
||||||
|
return t.Year()
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|||||||
@@ -490,6 +490,22 @@ func TestBuildTagMetadataUsesAlbumArtistOverride(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestBuildTagMetadataUsesAlbumContextTrackTotal(t *testing.T) {
|
||||||
|
meta := map[string]any{
|
||||||
|
"title": "ideal world (feat. higma)",
|
||||||
|
"track_number": float64(2),
|
||||||
|
"performer": map[string]any{"name": "Seren Azuma"},
|
||||||
|
"album": map[string]any{
|
||||||
|
"title": "YUKIHASU",
|
||||||
|
"artist": map[string]any{"name": "Seren Azuma"},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
tags := buildTagMetadata(meta, "ideal world (feat. higma)", "qobuz", "295525879", ripTrackOptions{total: 11})
|
||||||
|
if tags.TrackTotal != 11 {
|
||||||
|
t.Fatalf("track total = %d, want 11", tags.TrackTotal)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestBuildTagMetadataPlaylistOmitsDiscTags(t *testing.T) {
|
func TestBuildTagMetadataPlaylistOmitsDiscTags(t *testing.T) {
|
||||||
meta := map[string]any{
|
meta := map[string]any{
|
||||||
"title": "One Step Too Far",
|
"title": "One Step Too Far",
|
||||||
@@ -877,6 +893,36 @@ func TestBuildTagMetadataInitialKey(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestBuildTagMetadataArtistList(t *testing.T) {
|
||||||
|
meta := map[string]any{
|
||||||
|
"artist_names": []string{"Lost Frequencies", "Calum Scott", "Kungs"},
|
||||||
|
"performer": map[string]any{"name": "Lost Frequencies, Calum Scott & Kungs"},
|
||||||
|
"album": map[string]any{"title": "Album"},
|
||||||
|
}
|
||||||
|
|
||||||
|
tags := buildTagMetadata(meta, "Song", "beatport", "42", ripTrackOptions{})
|
||||||
|
if tags.Artist != "Lost Frequencies, Calum Scott & Kungs" {
|
||||||
|
t.Fatalf("artist=%q", tags.Artist)
|
||||||
|
}
|
||||||
|
if got := strings.Join(tags.Artists, ";"); got != "Lost Frequencies;Calum Scott;Kungs" {
|
||||||
|
t.Fatalf("artists=%q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTitleFromMetadataSkipsOriginalMix(t *testing.T) {
|
||||||
|
meta := map[string]any{"title": "Dance Done", "version": "Original Mix"}
|
||||||
|
if got := titleFromMetadata(meta, "42"); got != "Dance Done" {
|
||||||
|
t.Fatalf("titleFromMetadata()=%q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTitleFromMetadataIncludesNonOriginalMix(t *testing.T) {
|
||||||
|
meta := map[string]any{"title": "Dance Done", "version": "Extended Mix"}
|
||||||
|
if got := titleFromMetadata(meta, "42"); got != "Dance Done (Extended Mix)" {
|
||||||
|
t.Fatalf("titleFromMetadata()=%q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestNormalizeInitialKey(t *testing.T) {
|
func TestNormalizeInitialKey(t *testing.T) {
|
||||||
tests := map[string]string{
|
tests := map[string]string{
|
||||||
"C Major": "C",
|
"C Major": "C",
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package tag
|
package tag
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"encoding/binary"
|
||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
"os/exec"
|
"os/exec"
|
||||||
@@ -13,8 +14,11 @@ type Metadata struct {
|
|||||||
Title string
|
Title string
|
||||||
Album string
|
Album string
|
||||||
Artist string
|
Artist string
|
||||||
|
Artists []string
|
||||||
AlbumArtist string
|
AlbumArtist string
|
||||||
|
Compilation bool
|
||||||
OmitDiscTags bool
|
OmitDiscTags bool
|
||||||
|
Year int
|
||||||
TrackNumber int
|
TrackNumber int
|
||||||
DiscNumber int
|
DiscNumber int
|
||||||
TrackTotal int
|
TrackTotal int
|
||||||
@@ -71,6 +75,9 @@ func (t *Tagger) TagFLAC(path string, meta Metadata, coverPath string) error {
|
|||||||
_ = os.Remove(tmpPath)
|
_ = os.Remove(tmpPath)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
if err = applyMultiValueFLACTags(path, meta); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -192,9 +199,159 @@ func toTags(meta Metadata) map[string]string {
|
|||||||
if meta.DiscTotal > 0 {
|
if meta.DiscTotal > 0 {
|
||||||
tags["disctotal"] = strconv.Itoa(meta.DiscTotal)
|
tags["disctotal"] = strconv.Itoa(meta.DiscTotal)
|
||||||
}
|
}
|
||||||
|
if meta.Compilation {
|
||||||
|
tags["COMPILATION"] = "1"
|
||||||
|
}
|
||||||
|
if meta.Year > 0 {
|
||||||
|
tags["year"] = strconv.Itoa(meta.Year)
|
||||||
|
}
|
||||||
return tags
|
return tags
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func applyMultiValueFLACTags(path string, meta Metadata) error {
|
||||||
|
if strings.ToLower(strings.TrimPrefix(filepath.Ext(path), ".")) != "flac" || len(meta.Artists) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
st, err := os.Stat(path)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
data, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
updated, err := replaceFLACVorbisComments(data, "ARTISTS", meta.Artists)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if updated == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return os.WriteFile(path, updated, st.Mode())
|
||||||
|
}
|
||||||
|
|
||||||
|
type flacMetadataBlock struct {
|
||||||
|
isLast bool
|
||||||
|
blockType byte
|
||||||
|
data []byte
|
||||||
|
}
|
||||||
|
|
||||||
|
func replaceFLACVorbisComments(data []byte, key string, values []string) ([]byte, error) {
|
||||||
|
if len(data) < 4 || string(data[:4]) != "fLaC" {
|
||||||
|
return nil, fmt.Errorf("not a FLAC file")
|
||||||
|
}
|
||||||
|
|
||||||
|
blocks := []flacMetadataBlock{}
|
||||||
|
pos := 4
|
||||||
|
vorbisIndex := -1
|
||||||
|
for {
|
||||||
|
if pos+4 > len(data) {
|
||||||
|
return nil, fmt.Errorf("truncated FLAC metadata header")
|
||||||
|
}
|
||||||
|
header := data[pos]
|
||||||
|
blockType := header & 0x7f
|
||||||
|
length := int(data[pos+1])<<16 | int(data[pos+2])<<8 | int(data[pos+3])
|
||||||
|
pos += 4
|
||||||
|
if pos+length > len(data) {
|
||||||
|
return nil, fmt.Errorf("truncated FLAC metadata block")
|
||||||
|
}
|
||||||
|
if blockType == 4 {
|
||||||
|
vorbisIndex = len(blocks)
|
||||||
|
}
|
||||||
|
blocks = append(blocks, flacMetadataBlock{isLast: header&0x80 != 0, blockType: blockType, data: data[pos : pos+length]})
|
||||||
|
pos += length
|
||||||
|
if header&0x80 != 0 {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if vorbisIndex < 0 {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
commentBlock, err := replaceVorbisCommentValues(blocks[vorbisIndex].data, key, values)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
blocks[vorbisIndex].data = commentBlock
|
||||||
|
|
||||||
|
out := make([]byte, 0, len(data)+len(commentBlock)-len(blocks[vorbisIndex].data))
|
||||||
|
out = append(out, data[:4]...)
|
||||||
|
for _, block := range blocks {
|
||||||
|
if len(block.data) > 0xffffff {
|
||||||
|
return nil, fmt.Errorf("FLAC metadata block too large")
|
||||||
|
}
|
||||||
|
header := block.blockType
|
||||||
|
if block.isLast {
|
||||||
|
header |= 0x80
|
||||||
|
}
|
||||||
|
out = append(out, header, byte(len(block.data)>>16), byte(len(block.data)>>8), byte(len(block.data)))
|
||||||
|
out = append(out, block.data...)
|
||||||
|
}
|
||||||
|
out = append(out, data[pos:]...)
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func replaceVorbisCommentValues(data []byte, key string, values []string) ([]byte, error) {
|
||||||
|
if len(data) < 8 {
|
||||||
|
return nil, fmt.Errorf("truncated Vorbis comment block")
|
||||||
|
}
|
||||||
|
pos := 0
|
||||||
|
vendorLength := int(binary.LittleEndian.Uint32(data[pos:]))
|
||||||
|
pos += 4
|
||||||
|
if pos+vendorLength+4 > len(data) {
|
||||||
|
return nil, fmt.Errorf("truncated Vorbis vendor string")
|
||||||
|
}
|
||||||
|
vendor := data[pos : pos+vendorLength]
|
||||||
|
pos += vendorLength
|
||||||
|
commentCount := int(binary.LittleEndian.Uint32(data[pos:]))
|
||||||
|
pos += 4
|
||||||
|
|
||||||
|
comments := make([][]byte, 0, commentCount+len(values))
|
||||||
|
for i := 0; i < commentCount; i++ {
|
||||||
|
if pos+4 > len(data) {
|
||||||
|
return nil, fmt.Errorf("truncated Vorbis comment length")
|
||||||
|
}
|
||||||
|
commentLength := int(binary.LittleEndian.Uint32(data[pos:]))
|
||||||
|
pos += 4
|
||||||
|
if pos+commentLength > len(data) {
|
||||||
|
return nil, fmt.Errorf("truncated Vorbis comment")
|
||||||
|
}
|
||||||
|
comment := data[pos : pos+commentLength]
|
||||||
|
pos += commentLength
|
||||||
|
if !vorbisCommentKeyEqual(comment, key) {
|
||||||
|
comments = append(comments, comment)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, value := range values {
|
||||||
|
value = strings.TrimSpace(value)
|
||||||
|
if value != "" {
|
||||||
|
comments = append(comments, []byte(key+"="+value))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
out := make([]byte, 0, len(data))
|
||||||
|
out = appendUint32LE(out, uint32(len(vendor)))
|
||||||
|
out = append(out, vendor...)
|
||||||
|
out = appendUint32LE(out, uint32(len(comments)))
|
||||||
|
for _, comment := range comments {
|
||||||
|
out = appendUint32LE(out, uint32(len(comment)))
|
||||||
|
out = append(out, comment...)
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func vorbisCommentKeyEqual(comment []byte, key string) bool {
|
||||||
|
idx := strings.IndexByte(string(comment), '=')
|
||||||
|
if idx < 0 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return strings.EqualFold(string(comment[:idx]), key)
|
||||||
|
}
|
||||||
|
|
||||||
|
func appendUint32LE(out []byte, v uint32) []byte {
|
||||||
|
return append(out, byte(v), byte(v>>8), byte(v>>16), byte(v>>24))
|
||||||
|
}
|
||||||
|
|
||||||
func normalizeCopyright(in string) string {
|
func normalizeCopyright(in string) string {
|
||||||
out := strings.ReplaceAll(in, "(c)", "©")
|
out := strings.ReplaceAll(in, "(c)", "©")
|
||||||
out = strings.ReplaceAll(out, "(C)", "©")
|
out = strings.ReplaceAll(out, "(C)", "©")
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package tag
|
package tag
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"encoding/binary"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"testing"
|
"testing"
|
||||||
@@ -64,6 +65,102 @@ func TestToTagsTotalsAndSourceFields(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestToTagsArtistList(t *testing.T) {
|
||||||
|
tags := toTags(Metadata{Artist: "A, B & C", Artists: []string{"A", "B", "C"}})
|
||||||
|
if tags["artist"] != "A, B & C" {
|
||||||
|
t.Fatalf("artist tags = %+v", tags)
|
||||||
|
}
|
||||||
|
if _, ok := tags["ARTISTS"]; ok {
|
||||||
|
t.Fatalf("ARTISTS should be written as repeated FLAC comments, got %+v", tags)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestReplaceVorbisCommentValuesWritesRepeatedTags(t *testing.T) {
|
||||||
|
block := vorbisCommentBlock("vendor", []string{
|
||||||
|
"ARTIST=A, B & C",
|
||||||
|
"ARTISTS=A;B;C",
|
||||||
|
"TITLE=Song",
|
||||||
|
})
|
||||||
|
|
||||||
|
updated, err := replaceVorbisCommentValues(block, "ARTISTS", []string{"A", "B", "C"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("replaceVorbisCommentValues() error = %v", err)
|
||||||
|
}
|
||||||
|
comments := readVorbisComments(t, updated)
|
||||||
|
want := []string{"ARTIST=A, B & C", "TITLE=Song", "ARTISTS=A", "ARTISTS=B", "ARTISTS=C"}
|
||||||
|
if len(comments) != len(want) {
|
||||||
|
t.Fatalf("comments=%#v want %#v", comments, want)
|
||||||
|
}
|
||||||
|
for i := range want {
|
||||||
|
if comments[i] != want[i] {
|
||||||
|
t.Fatalf("comments=%#v want %#v", comments, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestReplaceFLACVorbisComments(t *testing.T) {
|
||||||
|
vorbis := vorbisCommentBlock("vendor", []string{"ARTISTS=A;B", "TITLE=Song"})
|
||||||
|
flac := append([]byte("fLaC"), flacBlockHeader(true, 4, len(vorbis))...)
|
||||||
|
flac = append(flac, vorbis...)
|
||||||
|
flac = append(flac, []byte("audio")...)
|
||||||
|
|
||||||
|
updated, err := replaceFLACVorbisComments(flac, "ARTISTS", []string{"A", "B"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("replaceFLACVorbisComments() error = %v", err)
|
||||||
|
}
|
||||||
|
if string(updated[len(updated)-5:]) != "audio" {
|
||||||
|
t.Fatalf("audio payload not preserved")
|
||||||
|
}
|
||||||
|
length := int(updated[5])<<16 | int(updated[6])<<8 | int(updated[7])
|
||||||
|
comments := readVorbisComments(t, updated[8:8+length])
|
||||||
|
want := []string{"TITLE=Song", "ARTISTS=A", "ARTISTS=B"}
|
||||||
|
if len(comments) != len(want) {
|
||||||
|
t.Fatalf("comments=%#v want %#v", comments, want)
|
||||||
|
}
|
||||||
|
for i := range want {
|
||||||
|
if comments[i] != want[i] {
|
||||||
|
t.Fatalf("comments=%#v want %#v", comments, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func vorbisCommentBlock(vendor string, comments []string) []byte {
|
||||||
|
out := []byte{}
|
||||||
|
out = appendUint32LE(out, uint32(len(vendor)))
|
||||||
|
out = append(out, vendor...)
|
||||||
|
out = appendUint32LE(out, uint32(len(comments)))
|
||||||
|
for _, comment := range comments {
|
||||||
|
out = appendUint32LE(out, uint32(len(comment)))
|
||||||
|
out = append(out, comment...)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func flacBlockHeader(last bool, blockType byte, length int) []byte {
|
||||||
|
header := blockType
|
||||||
|
if last {
|
||||||
|
header |= 0x80
|
||||||
|
}
|
||||||
|
return []byte{header, byte(length >> 16), byte(length >> 8), byte(length)}
|
||||||
|
}
|
||||||
|
|
||||||
|
func readVorbisComments(t *testing.T, block []byte) []string {
|
||||||
|
t.Helper()
|
||||||
|
pos := 0
|
||||||
|
vendorLength := int(binary.LittleEndian.Uint32(block[pos:]))
|
||||||
|
pos += 4 + vendorLength
|
||||||
|
count := int(binary.LittleEndian.Uint32(block[pos:]))
|
||||||
|
pos += 4
|
||||||
|
comments := make([]string, 0, count)
|
||||||
|
for i := 0; i < count; i++ {
|
||||||
|
length := int(binary.LittleEndian.Uint32(block[pos:]))
|
||||||
|
pos += 4
|
||||||
|
comments = append(comments, string(block[pos:pos+length]))
|
||||||
|
pos += length
|
||||||
|
}
|
||||||
|
return comments
|
||||||
|
}
|
||||||
|
|
||||||
func TestBuildFFmpegArgsWithCover(t *testing.T) {
|
func TestBuildFFmpegArgsWithCover(t *testing.T) {
|
||||||
tmp := t.TempDir()
|
tmp := t.TempDir()
|
||||||
cover := filepath.Join(tmp, "cover.jpg")
|
cover := filepath.Join(tmp, "cover.jpg")
|
||||||
|
|||||||
@@ -480,14 +480,16 @@ func (c *Client) rawRequest(ctx context.Context, method, endpoint string, params
|
|||||||
|
|
||||||
func (c *Client) normalizeRelease(raw map[string]any, tracks []any) map[string]any {
|
func (c *Client) normalizeRelease(raw map[string]any, tracks []any) map[string]any {
|
||||||
id := jsonutil.StringFromAny(raw["id"])
|
id := jsonutil.StringFromAny(raw["id"])
|
||||||
artist := c.releaseArtistName(raw["artists"])
|
artist := c.releaseArtistNameForTracks(raw["artists"], tracks)
|
||||||
|
trackRelease := cloneMap(raw)
|
||||||
|
trackRelease["album_artist_name"] = artist
|
||||||
items := make([]any, 0, len(tracks))
|
items := make([]any, 0, len(tracks))
|
||||||
for _, entry := range tracks {
|
for _, entry := range tracks {
|
||||||
track, ok := entry.(map[string]any)
|
track, ok := entry.(map[string]any)
|
||||||
if !ok {
|
if !ok {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
track["release"] = raw
|
track["release"] = trackRelease
|
||||||
items = append(items, c.normalizeTrack(track))
|
items = append(items, c.normalizeTrack(track))
|
||||||
}
|
}
|
||||||
return map[string]any{
|
return map[string]any{
|
||||||
@@ -507,9 +509,13 @@ func (c *Client) normalizeRelease(raw map[string]any, tracks []any) map[string]a
|
|||||||
|
|
||||||
func (c *Client) normalizeTrack(raw map[string]any) map[string]any {
|
func (c *Client) normalizeTrack(raw map[string]any) map[string]any {
|
||||||
release := mapAny(raw["release"])
|
release := mapAny(raw["release"])
|
||||||
artistName := c.joinArtists(raw["artists"])
|
trackArtistNames := artistNames(raw["artists"])
|
||||||
|
artistName := displayArtistNames(trackArtistNames)
|
||||||
artistID := firstArtistID(raw["artists"])
|
artistID := firstArtistID(raw["artists"])
|
||||||
albumArtist := c.releaseArtistName(release["artists"])
|
albumArtist := strings.TrimSpace(jsonutil.StringFromAny(release["album_artist_name"]))
|
||||||
|
if albumArtist == "" {
|
||||||
|
albumArtist = c.releaseArtistName(release["artists"])
|
||||||
|
}
|
||||||
if albumArtist == "" {
|
if albumArtist == "" {
|
||||||
albumArtist = artistName
|
albumArtist = artistName
|
||||||
}
|
}
|
||||||
@@ -524,6 +530,7 @@ func (c *Client) normalizeTrack(raw map[string]any) map[string]any {
|
|||||||
"version": jsonutil.StringFromAny(raw["mix_name"]),
|
"version": jsonutil.StringFromAny(raw["mix_name"]),
|
||||||
"artist": map[string]any{"id": artistID, "name": artistName},
|
"artist": map[string]any{"id": artistID, "name": artistName},
|
||||||
"performer": map[string]any{"id": artistID, "name": artistName},
|
"performer": map[string]any{"id": artistID, "name": artistName},
|
||||||
|
"artist_names": trackArtistNames,
|
||||||
"album": map[string]any{"id": jsonutil.StringFromAny(release["id"]), "title": jsonutil.StringFromAny(release["name"]), "artist": map[string]any{"name": albumArtist}, "image": imageMap(release["image"]), "release_date_original": date},
|
"album": map[string]any{"id": jsonutil.StringFromAny(release["id"]), "title": jsonutil.StringFromAny(release["name"]), "artist": map[string]any{"name": albumArtist}, "image": imageMap(release["image"]), "release_date_original": date},
|
||||||
"track_number": jsonutil.IntFromAny(raw["number"]),
|
"track_number": jsonutil.IntFromAny(raw["number"]),
|
||||||
"tracks_count": jsonutil.IntFromAny(release["track_count"]),
|
"tracks_count": jsonutil.IntFromAny(release["track_count"]),
|
||||||
@@ -544,11 +551,12 @@ func (c *Client) normalizeTrack(raw map[string]any) map[string]any {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (c *Client) normalizeTrackListItem(raw map[string]any) map[string]any {
|
func (c *Client) normalizeTrackListItem(raw map[string]any) map[string]any {
|
||||||
|
names := artistNames(raw["artists"])
|
||||||
return map[string]any{
|
return map[string]any{
|
||||||
"id": jsonutil.StringFromAny(raw["id"]),
|
"id": jsonutil.StringFromAny(raw["id"]),
|
||||||
"title": jsonutil.StringFromAny(raw["name"]),
|
"title": jsonutil.StringFromAny(raw["name"]),
|
||||||
"version": jsonutil.StringFromAny(raw["mix_name"]),
|
"version": jsonutil.StringFromAny(raw["mix_name"]),
|
||||||
"artist": map[string]any{"name": c.joinArtists(raw["artists"])},
|
"artist": map[string]any{"name": displayArtistNames(names)},
|
||||||
"album": map[string]any{"id": jsonutil.NestedString(raw, "release", "id"), "title": jsonutil.NestedString(raw, "release", "name")},
|
"album": map[string]any{"id": jsonutil.NestedString(raw, "release", "id"), "title": jsonutil.NestedString(raw, "release", "name")},
|
||||||
"track_number": jsonutil.IntFromAny(raw["number"]),
|
"track_number": jsonutil.IntFromAny(raw["number"]),
|
||||||
}
|
}
|
||||||
@@ -607,6 +615,9 @@ func playlistMetadata(raw map[string]any, tracks []any) map[string]any {
|
|||||||
"title": name,
|
"title": name,
|
||||||
"tracks_count": firstPositiveInt(jsonutil.IntFromAny(raw["track_count"]), len(tracks)),
|
"tracks_count": firstPositiveInt(jsonutil.IntFromAny(raw["track_count"]), len(tracks)),
|
||||||
"image": imageMap(raw["image"]),
|
"image": imageMap(raw["image"]),
|
||||||
|
"publish_date": jsonutil.StringFromAny(raw["publish_date"]),
|
||||||
|
"new_release_date": jsonutil.StringFromAny(raw["new_release_date"]),
|
||||||
|
"release_date": jsonutil.StringFromAny(raw["release_date"]),
|
||||||
"tracks": map[string]any{"items": tracks},
|
"tracks": map[string]any{"items": tracks},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -653,7 +664,7 @@ func audioProfile(quality, streamQuality string) (provider.AudioProfile, string)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Client) joinArtists(v any) string {
|
func artistNames(v any) []string {
|
||||||
items := sliceAny(v)
|
items := sliceAny(v)
|
||||||
names := make([]string, 0, len(items))
|
names := make([]string, 0, len(items))
|
||||||
for _, raw := range items {
|
for _, raw := range items {
|
||||||
@@ -665,7 +676,20 @@ func (c *Client) joinArtists(v any) string {
|
|||||||
names = append(names, name)
|
names = append(names, name)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return strings.Join(names, artistSeparator(c.cfg.Session.Metadata.ArtistSeparator))
|
return names
|
||||||
|
}
|
||||||
|
|
||||||
|
func displayArtistNames(names []string) string {
|
||||||
|
switch len(names) {
|
||||||
|
case 0:
|
||||||
|
return ""
|
||||||
|
case 1:
|
||||||
|
return names[0]
|
||||||
|
case 2:
|
||||||
|
return names[0] + " & " + names[1]
|
||||||
|
default:
|
||||||
|
return strings.Join(names[:len(names)-1], ", ") + " & " + names[len(names)-1]
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Client) releaseArtistName(v any) string {
|
func (c *Client) releaseArtistName(v any) string {
|
||||||
@@ -674,14 +698,72 @@ func (c *Client) releaseArtistName(v any) string {
|
|||||||
if threshold >= 0 && len(items) > threshold {
|
if threshold >= 0 && len(items) > threshold {
|
||||||
return "Various Artists"
|
return "Various Artists"
|
||||||
}
|
}
|
||||||
return c.joinArtists(v)
|
return displayArtistNames(artistNames(v))
|
||||||
}
|
}
|
||||||
|
|
||||||
func artistSeparator(separator string) string {
|
func (c *Client) releaseArtistNameForTracks(releaseArtists any, tracks []any) string {
|
||||||
if separator == "" {
|
common := commonReleaseArtists(releaseArtists, tracks)
|
||||||
return "; "
|
if len(common) > 0 {
|
||||||
|
return displayArtistNames(artistNames(common))
|
||||||
}
|
}
|
||||||
return separator
|
return c.releaseArtistName(releaseArtists)
|
||||||
|
}
|
||||||
|
|
||||||
|
func commonReleaseArtists(releaseArtists any, tracks []any) []any {
|
||||||
|
items := sliceAny(releaseArtists)
|
||||||
|
if len(items) == 0 || len(tracks) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
counts := map[string]int{}
|
||||||
|
trackCount := 0
|
||||||
|
for _, rawTrack := range tracks {
|
||||||
|
track, ok := rawTrack.(map[string]any)
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
trackCount++
|
||||||
|
seen := map[string]bool{}
|
||||||
|
for _, rawArtist := range sliceAny(track["artists"]) {
|
||||||
|
if key := artistIdentity(rawArtist); key != "" {
|
||||||
|
seen[key] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for key := range seen {
|
||||||
|
counts[key]++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if trackCount == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
common := make([]any, 0)
|
||||||
|
for _, rawArtist := range items {
|
||||||
|
if key := artistIdentity(rawArtist); key != "" && counts[key] == trackCount {
|
||||||
|
common = append(common, rawArtist)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return common
|
||||||
|
}
|
||||||
|
|
||||||
|
func artistIdentity(raw any) string {
|
||||||
|
m, ok := raw.(map[string]any)
|
||||||
|
if !ok {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
if id := strings.TrimSpace(jsonutil.StringFromAny(m["id"])); id != "" {
|
||||||
|
return "id:" + id
|
||||||
|
}
|
||||||
|
if name := strings.TrimSpace(jsonutil.StringFromAny(m["name"])); name != "" {
|
||||||
|
return "name:" + strings.ToLower(name)
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func cloneMap(in map[string]any) map[string]any {
|
||||||
|
out := make(map[string]any, len(in))
|
||||||
|
for k, v := range in {
|
||||||
|
out[k] = v
|
||||||
|
}
|
||||||
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
func firstArtistID(v any) string {
|
func firstArtistID(v any) string {
|
||||||
|
|||||||
@@ -114,7 +114,7 @@ func TestAlbumMetadataCollapsesManyReleaseArtists(t *testing.T) {
|
|||||||
writeJSON(t, w, map[string]any{
|
writeJSON(t, w, map[string]any{
|
||||||
"id": 7,
|
"id": 7,
|
||||||
"name": "Compilation",
|
"name": "Compilation",
|
||||||
"track_count": 1,
|
"track_count": 2,
|
||||||
"artists": []any{
|
"artists": []any{
|
||||||
map[string]any{"id": 1, "name": "A"},
|
map[string]any{"id": 1, "name": "A"},
|
||||||
map[string]any{"id": 2, "name": "B"},
|
map[string]any{"id": 2, "name": "B"},
|
||||||
@@ -125,12 +125,10 @@ func TestAlbumMetadataCollapsesManyReleaseArtists(t *testing.T) {
|
|||||||
case "/catalog/releases/7/tracks/":
|
case "/catalog/releases/7/tracks/":
|
||||||
writeJSON(t, w, map[string]any{
|
writeJSON(t, w, map[string]any{
|
||||||
"next": nil,
|
"next": nil,
|
||||||
"results": []any{map[string]any{
|
"results": []any{
|
||||||
"id": 42,
|
map[string]any{"id": 42, "name": "Track A", "number": 1, "artists": []any{map[string]any{"id": 1, "name": "A"}}},
|
||||||
"name": "Track Name",
|
map[string]any{"id": 43, "name": "Track B", "number": 2, "artists": []any{map[string]any{"id": 2, "name": "B"}}},
|
||||||
"number": 1,
|
},
|
||||||
"artists": []any{map[string]any{"id": 1, "name": "A"}},
|
|
||||||
}},
|
|
||||||
})
|
})
|
||||||
default:
|
default:
|
||||||
t.Fatalf("unexpected path %q", r.URL.Path)
|
t.Fatalf("unexpected path %q", r.URL.Path)
|
||||||
@@ -154,6 +152,52 @@ func TestAlbumMetadataCollapsesManyReleaseArtists(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestAlbumMetadataUsesArtistPresentOnEveryTrack(t *testing.T) {
|
||||||
|
c, closeServer := newTestClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
switch r.URL.Path {
|
||||||
|
case "/catalog/releases/7/":
|
||||||
|
writeJSON(t, w, map[string]any{
|
||||||
|
"id": 7,
|
||||||
|
"name": "Artist Album",
|
||||||
|
"track_count": 3,
|
||||||
|
"artists": []any{
|
||||||
|
map[string]any{"id": 1, "name": "Main"},
|
||||||
|
map[string]any{"id": 2, "name": "Guest A"},
|
||||||
|
map[string]any{"id": 3, "name": "Guest B"},
|
||||||
|
map[string]any{"id": 4, "name": "Guest C"},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
case "/catalog/releases/7/tracks/":
|
||||||
|
writeJSON(t, w, map[string]any{
|
||||||
|
"next": nil,
|
||||||
|
"results": []any{
|
||||||
|
map[string]any{"id": 42, "name": "Track A", "number": 1, "artists": []any{map[string]any{"id": 1, "name": "Main"}, map[string]any{"id": 2, "name": "Guest A"}}},
|
||||||
|
map[string]any{"id": 43, "name": "Track B", "number": 2, "artists": []any{map[string]any{"id": 1, "name": "Main"}, map[string]any{"id": 3, "name": "Guest B"}}},
|
||||||
|
map[string]any{"id": 44, "name": "Track C", "number": 3, "artists": []any{map[string]any{"id": 1, "name": "Main"}, map[string]any{"id": 4, "name": "Guest C"}}},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
default:
|
||||||
|
t.Fatalf("unexpected path %q", r.URL.Path)
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
defer closeServer()
|
||||||
|
|
||||||
|
meta, err := c.GetMetadata(context.Background(), "7", "album")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("GetMetadata() error = %v", err)
|
||||||
|
}
|
||||||
|
artist := meta["artist"].(map[string]any)
|
||||||
|
if artist["name"] != "Main" {
|
||||||
|
t.Fatalf("album artist = %q, want Main", artist["name"])
|
||||||
|
}
|
||||||
|
track := meta["tracks"].(map[string]any)["items"].([]any)[0].(map[string]any)
|
||||||
|
album := track["album"].(map[string]any)
|
||||||
|
albumArtist := album["artist"].(map[string]any)
|
||||||
|
if albumArtist["name"] != "Main" {
|
||||||
|
t.Fatalf("track album artist = %q, want Main", albumArtist["name"])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestReleaseArtistCollapseCanBeDisabled(t *testing.T) {
|
func TestReleaseArtistCollapseCanBeDisabled(t *testing.T) {
|
||||||
cfg := &config.Config{Session: config.DefaultConfigData(), File: config.DefaultConfigData()}
|
cfg := &config.Config{Session: config.DefaultConfigData(), File: config.DefaultConfigData()}
|
||||||
cfg.Session.Beatport.VariousArtistsThreshold = -1
|
cfg.Session.Beatport.VariousArtistsThreshold = -1
|
||||||
@@ -164,21 +208,19 @@ func TestReleaseArtistCollapseCanBeDisabled(t *testing.T) {
|
|||||||
map[string]any{"name": "C"},
|
map[string]any{"name": "C"},
|
||||||
map[string]any{"name": "D"},
|
map[string]any{"name": "D"},
|
||||||
})
|
})
|
||||||
if got != "A; B; C; D" {
|
if got != "A, B, C & D" {
|
||||||
t.Fatalf("releaseArtistName() = %q", got)
|
t.Fatalf("releaseArtistName() = %q", got)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestArtistSeparatorCanBeConfigured(t *testing.T) {
|
func TestDisplayArtistNamesUsesCreditPunctuation(t *testing.T) {
|
||||||
cfg := &config.Config{Session: config.DefaultConfigData(), File: config.DefaultConfigData()}
|
got := displayArtistNames(artistNames([]any{
|
||||||
cfg.Session.Metadata.ArtistSeparator = " / "
|
|
||||||
c := New(cfg)
|
|
||||||
got := c.joinArtists([]any{
|
|
||||||
map[string]any{"name": "A"},
|
map[string]any{"name": "A"},
|
||||||
map[string]any{"name": "B"},
|
map[string]any{"name": "B"},
|
||||||
})
|
map[string]any{"name": "C"},
|
||||||
if got != "A / B" {
|
}))
|
||||||
t.Fatalf("joinArtists() = %q", got)
|
if got != "A, B & C" {
|
||||||
|
t.Fatalf("displayArtistNames() = %q", got)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -364,40 +364,60 @@ func qobuzDownloadExtension(resp map[string]any, quality int, streamURL string)
|
|||||||
}
|
}
|
||||||
|
|
||||||
func qobuzAudioProfile(resp map[string]any, requestedQuality int, ext string) provider.AudioProfile {
|
func qobuzAudioProfile(resp map[string]any, requestedQuality int, ext string) provider.AudioProfile {
|
||||||
|
exactBitDepth, _ := intValue(firstNonNil(resp["bit_depth"], resp["bits_depth"], resp["maximum_bit_depth"]))
|
||||||
|
exactSampling, _ := floatValue(firstNonNil(resp["sampling_rate"], resp["sample_rate"], resp["maximum_sampling_rate"]))
|
||||||
if formatID, ok := intValue(resp["format_id"]); ok {
|
if formatID, ok := intValue(resp["format_id"]); ok {
|
||||||
switch formatID {
|
switch formatID {
|
||||||
case 5:
|
case 5:
|
||||||
|
if exactBitDepth == 0 {
|
||||||
|
exactBitDepth = 16
|
||||||
|
}
|
||||||
|
if exactSampling == 0 {
|
||||||
|
exactSampling = 44.1
|
||||||
|
}
|
||||||
return provider.AudioProfile{
|
return provider.AudioProfile{
|
||||||
Container: "MP3",
|
Container: "MP3",
|
||||||
Codec: "MP3",
|
Codec: "MP3",
|
||||||
Quality: "HIGH",
|
Quality: "HIGH",
|
||||||
BitDepth: 16,
|
BitDepth: exactBitDepth,
|
||||||
SamplingRate: "44.1",
|
SamplingRate: formatSamplingRate(exactSampling),
|
||||||
BitrateKbps: 320,
|
BitrateKbps: 320,
|
||||||
}
|
}
|
||||||
case 6:
|
case 6:
|
||||||
|
if exactBitDepth == 0 {
|
||||||
|
exactBitDepth = 16
|
||||||
|
}
|
||||||
|
if exactSampling == 0 {
|
||||||
|
exactSampling = 44.1
|
||||||
|
}
|
||||||
return provider.AudioProfile{
|
return provider.AudioProfile{
|
||||||
Container: "FLAC",
|
Container: "FLAC",
|
||||||
Codec: "FLAC",
|
Codec: "FLAC",
|
||||||
Quality: "LOSSLESS",
|
Quality: "LOSSLESS",
|
||||||
BitDepth: 16,
|
BitDepth: exactBitDepth,
|
||||||
SamplingRate: "44.1",
|
SamplingRate: formatSamplingRate(exactSampling),
|
||||||
}
|
}
|
||||||
case 7:
|
case 7:
|
||||||
|
if exactBitDepth == 0 {
|
||||||
|
exactBitDepth = 24
|
||||||
|
}
|
||||||
return provider.AudioProfile{
|
return provider.AudioProfile{
|
||||||
Container: "FLAC",
|
Container: "FLAC",
|
||||||
Codec: "FLAC",
|
Codec: "FLAC",
|
||||||
Quality: "HI_RES",
|
Quality: "HI_RES",
|
||||||
BitDepth: 24,
|
BitDepth: exactBitDepth,
|
||||||
SamplingRate: "96",
|
SamplingRate: formatSamplingRate(exactSampling),
|
||||||
}
|
}
|
||||||
case 27:
|
case 27:
|
||||||
|
if exactBitDepth == 0 {
|
||||||
|
exactBitDepth = 24
|
||||||
|
}
|
||||||
return provider.AudioProfile{
|
return provider.AudioProfile{
|
||||||
Container: "FLAC",
|
Container: "FLAC",
|
||||||
Codec: "FLAC",
|
Codec: "FLAC",
|
||||||
Quality: "HI_RES",
|
Quality: "HI_RES",
|
||||||
BitDepth: 24,
|
BitDepth: exactBitDepth,
|
||||||
SamplingRate: "192",
|
SamplingRate: formatSamplingRate(exactSampling),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -438,6 +458,22 @@ func qobuzAudioProfile(resp map[string]any, requestedQuality int, ext string) pr
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func firstNonNil(vals ...any) any {
|
||||||
|
for _, v := range vals {
|
||||||
|
if v != nil {
|
||||||
|
return v
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func formatSamplingRate(v float64) string {
|
||||||
|
if v <= 0 {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return strconv.FormatFloat(v, 'f', -1, 64)
|
||||||
|
}
|
||||||
|
|
||||||
func (c *Client) Close() error {
|
func (c *Client) Close() error {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -577,11 +613,13 @@ func (c *Client) getPlaylist(ctx context.Context, playlistID string) (map[string
|
|||||||
|
|
||||||
total, _ := intValue(resp["tracks_count"])
|
total, _ := intValue(resp["tracks_count"])
|
||||||
if total <= pageLimit {
|
if total <= pageLimit {
|
||||||
|
normalizePlaylistImage(resp)
|
||||||
return resp, nil
|
return resp, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
tracksObj, ok := mapValue(resp["tracks"])
|
tracksObj, ok := mapValue(resp["tracks"])
|
||||||
if !ok {
|
if !ok {
|
||||||
|
normalizePlaylistImage(resp)
|
||||||
return resp, nil
|
return resp, nil
|
||||||
}
|
}
|
||||||
items, ok := tracksObj["items"].([]any)
|
items, ok := tracksObj["items"].([]any)
|
||||||
@@ -617,9 +655,25 @@ func (c *Client) getPlaylist(ctx context.Context, playlistID string) (map[string
|
|||||||
|
|
||||||
tracksObj["items"] = items
|
tracksObj["items"] = items
|
||||||
resp["tracks"] = tracksObj
|
resp["tracks"] = tracksObj
|
||||||
|
normalizePlaylistImage(resp)
|
||||||
return resp, nil
|
return resp, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func normalizePlaylistImage(resp map[string]any) {
|
||||||
|
if resp["image"] != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
rect, ok := resp["image_rectangle"].([]any)
|
||||||
|
if !ok || len(rect) == 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
url, ok := rect[0].(string)
|
||||||
|
if !ok || url == "" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
resp["image"] = map[string]any{"original": url, "large": url}
|
||||||
|
}
|
||||||
|
|
||||||
func (c *Client) getLabel(ctx context.Context, labelID string) (map[string]any, error) {
|
func (c *Client) getLabel(ctx context.Context, labelID string) (map[string]any, error) {
|
||||||
pageLimit := 500
|
pageLimit := 500
|
||||||
params := url.Values{}
|
params := url.Values{}
|
||||||
|
|||||||
@@ -371,6 +371,24 @@ func TestGetDownloadableUsesReturnedURLExtension(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestQobuzAudioProfileUsesExactReturnedQuality(t *testing.T) {
|
||||||
|
profile := qobuzAudioProfile(map[string]any{
|
||||||
|
"format_id": float64(7),
|
||||||
|
"bit_depth": float64(24),
|
||||||
|
"sampling_rate": float64(44.1),
|
||||||
|
}, 4, "flac")
|
||||||
|
if profile.BitDepth != 24 || profile.SamplingRate != "44.1" || profile.Quality != "HI_RES" {
|
||||||
|
t.Fatalf("unexpected profile: %+v", profile)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestQobuzAudioProfileAvoidsGuessingHiResSampleRate(t *testing.T) {
|
||||||
|
profile := qobuzAudioProfile(map[string]any{"format_id": float64(7)}, 4, "flac")
|
||||||
|
if profile.BitDepth != 24 || profile.SamplingRate != "" || profile.Quality != "HI_RES" {
|
||||||
|
t.Fatalf("unexpected profile: %+v", profile)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func qobuzSecretSig(requestTS, secret string) string {
|
func qobuzSecretSig(requestTS, secret string) string {
|
||||||
raw := "trackgetFileUrlformat_id27intentstreamtrack_id19512574" + requestTS + secret
|
raw := "trackgetFileUrlformat_id27intentstreamtrack_id19512574" + requestTS + secret
|
||||||
hash := md5.Sum([]byte(raw))
|
hash := md5.Sum([]byte(raw))
|
||||||
|
|||||||
@@ -564,7 +564,8 @@ func resultMap(resp map[string]any) map[string]any {
|
|||||||
func normalizeTrack(raw map[string]any, fallbackID string, artistSeparator string) map[string]any {
|
func normalizeTrack(raw map[string]any, fallbackID string, artistSeparator string) map[string]any {
|
||||||
trackID := canonicalTrackRefFromRaw(raw, fallbackID)
|
trackID := canonicalTrackRefFromRaw(raw, fallbackID)
|
||||||
albumRaw := firstAlbum(raw)
|
albumRaw := firstAlbum(raw)
|
||||||
artistName := joinArtists(raw, artistSeparator)
|
artistNames := artistNames(raw)
|
||||||
|
artistName := displayArtistNames(artistNames)
|
||||||
albumArtist := joinAlbumArtists(albumRaw, artistSeparator)
|
albumArtist := joinAlbumArtists(albumRaw, artistSeparator)
|
||||||
if albumArtist == "" {
|
if albumArtist == "" {
|
||||||
albumArtist = artistName
|
albumArtist = artistName
|
||||||
@@ -589,6 +590,7 @@ func normalizeTrack(raw map[string]any, fallbackID string, artistSeparator strin
|
|||||||
"source_track_id": jsonutil.StringFromAny(raw["realId"]),
|
"source_track_id": jsonutil.StringFromAny(raw["realId"]),
|
||||||
"performer": map[string]any{"name": artistName},
|
"performer": map[string]any{"name": artistName},
|
||||||
"artist": map[string]any{"name": artistName, "id": firstArtistID(raw)},
|
"artist": map[string]any{"name": artistName, "id": firstArtistID(raw)},
|
||||||
|
"artist_names": artistNames,
|
||||||
"album": normalizeAlbumSummary(albumRaw, albumArtist),
|
"album": normalizeAlbumSummary(albumRaw, albumArtist),
|
||||||
"image": imageMapFromTrack(raw, albumRaw),
|
"image": imageMapFromTrack(raw, albumRaw),
|
||||||
"cover": imageMapFromTrack(raw, albumRaw),
|
"cover": imageMapFromTrack(raw, albumRaw),
|
||||||
@@ -769,6 +771,10 @@ func firstArtistID(raw map[string]any) string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func joinArtists(raw map[string]any, artistSeparator string) string {
|
func joinArtists(raw map[string]any, artistSeparator string) string {
|
||||||
|
return displayArtistNames(artistNames(raw))
|
||||||
|
}
|
||||||
|
|
||||||
|
func artistNames(raw map[string]any) []string {
|
||||||
artists, _ := raw["artists"].([]any)
|
artists, _ := raw["artists"].([]any)
|
||||||
parts := make([]string, 0, len(artists))
|
parts := make([]string, 0, len(artists))
|
||||||
for _, entry := range artists {
|
for _, entry := range artists {
|
||||||
@@ -780,13 +786,17 @@ func joinArtists(raw map[string]any, artistSeparator string) string {
|
|||||||
parts = append(parts, name)
|
parts = append(parts, name)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return strings.Join(parts, artistSeparator)
|
return parts
|
||||||
}
|
}
|
||||||
|
|
||||||
func joinAlbumArtists(albumRaw map[string]any, artistSeparator string) string {
|
func joinAlbumArtists(albumRaw map[string]any, artistSeparator string) string {
|
||||||
if len(albumRaw) == 0 {
|
if len(albumRaw) == 0 {
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
return displayArtistNames(albumArtistNames(albumRaw))
|
||||||
|
}
|
||||||
|
|
||||||
|
func albumArtistNames(albumRaw map[string]any) []string {
|
||||||
artists, _ := albumRaw["artists"].([]any)
|
artists, _ := albumRaw["artists"].([]any)
|
||||||
parts := make([]string, 0, len(artists))
|
parts := make([]string, 0, len(artists))
|
||||||
for _, entry := range artists {
|
for _, entry := range artists {
|
||||||
@@ -798,7 +808,20 @@ func joinAlbumArtists(albumRaw map[string]any, artistSeparator string) string {
|
|||||||
parts = append(parts, name)
|
parts = append(parts, name)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return strings.Join(parts, artistSeparator)
|
return parts
|
||||||
|
}
|
||||||
|
|
||||||
|
func displayArtistNames(names []string) string {
|
||||||
|
switch len(names) {
|
||||||
|
case 0:
|
||||||
|
return ""
|
||||||
|
case 1:
|
||||||
|
return names[0]
|
||||||
|
case 2:
|
||||||
|
return names[0] + " & " + names[1]
|
||||||
|
default:
|
||||||
|
return strings.Join(names[:len(names)-1], ", ") + " & " + names[len(names)-1]
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Client) artistSeparator() string {
|
func (c *Client) artistSeparator() string {
|
||||||
|
|||||||
@@ -155,12 +155,23 @@ func TestGetMetadataTrackUsesModernTracksEndpoint(t *testing.T) {
|
|||||||
if album, _ := meta["album"].(map[string]any); jsonutil.StringFromAny(album["title"]) != "OutRun" {
|
if album, _ := meta["album"].(map[string]any); jsonutil.StringFromAny(album["title"]) != "OutRun" {
|
||||||
t.Fatalf("unexpected album: %+v", album)
|
t.Fatalf("unexpected album: %+v", album)
|
||||||
}
|
}
|
||||||
if artist := jsonutil.NestedString(meta, "artist", "name"); artist != "Kavinsky; Lovefoxxx" {
|
if artist := jsonutil.NestedString(meta, "artist", "name"); artist != "Kavinsky & Lovefoxxx" {
|
||||||
t.Fatalf("artist = %q", artist)
|
t.Fatalf("artist = %q", artist)
|
||||||
}
|
}
|
||||||
if albumArtist := jsonutil.NestedString(meta, "album", "artist", "name"); albumArtist != "Kavinsky; Lovefoxxx" {
|
if albumArtist := jsonutil.NestedString(meta, "album", "artist", "name"); albumArtist != "Kavinsky & Lovefoxxx" {
|
||||||
t.Fatalf("album artist = %q", albumArtist)
|
t.Fatalf("album artist = %q", albumArtist)
|
||||||
}
|
}
|
||||||
|
artists, _ := meta["artist_names"].([]string)
|
||||||
|
if strings.Join(artists, ";") != "Kavinsky;Lovefoxxx" {
|
||||||
|
t.Fatalf("artist_names = %#v", artists)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDisplayArtistNamesUsesCreditPunctuation(t *testing.T) {
|
||||||
|
got := displayArtistNames([]string{"A", "B", "C"})
|
||||||
|
if got != "A, B & C" {
|
||||||
|
t.Fatalf("displayArtistNames() = %q", got)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestLegacyDirectURLBuildsPlayableMP3URL(t *testing.T) {
|
func TestLegacyDirectURLBuildsPlayableMP3URL(t *testing.T) {
|
||||||
|
|||||||
Reference in New Issue
Block a user