Files
AppleSync/internal/qobuz/client.go
T
2026-11-26 15:11:41 +01:00

304 lines
8.2 KiB
Go

// Package qobuz implements the small part of Qobuz's private API that
// applesync needs: album search and album detail. Only the public app id is
// required; no user login or request signing is used.
package qobuz
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"regexp"
"strconv"
"strings"
"sync"
"time"
"applesync/internal/model"
)
const (
defaultBaseURL = "https://www.qobuz.com/api.json/0.2"
userAgent = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0 Safari/537.36"
)
type Client struct {
http *http.Client
appID string
apiBase string
minDelay time.Duration
mu sync.Mutex
next time.Time
logf func(string, ...any)
}
func New(appID string) *Client {
return &Client{
http: &http.Client{Timeout: 30 * time.Second},
appID: strings.TrimSpace(appID),
apiBase: defaultBaseURL,
minDelay: 150 * time.Millisecond,
}
}
func (c *Client) SetLogf(fn func(string, ...any)) { c.logf = fn }
func (c *Client) log(format string, args ...any) {
if c.logf != nil {
c.logf(format, args...)
}
}
// ResolveAppID returns the configured app id, or scrapes the public one from
// play.qobuz.com if none was configured.
func ResolveAppID(ctx context.Context, configured string) (string, error) {
configured = strings.TrimSpace(configured)
if configured != "" {
return configured, nil
}
appID, err := scrapeAppID(ctx)
if err != nil {
return "", fmt.Errorf("Qobuz app id: %w; set [qobuz].app_id in the config", err)
}
return appID, nil
}
func scrapeAppID(ctx context.Context) (string, error) {
hc := &http.Client{Timeout: 30 * time.Second}
login, err := fetchText(ctx, hc, "https://play.qobuz.com/login")
if err != nil {
return "", err
}
bundleRe := regexp.MustCompile(`<script src="(/resources/\d+\.\d+\.\d+-[a-z]\d{3}/bundle\.js)"></script>`)
match := bundleRe.FindStringSubmatch(login)
if len(match) < 2 {
return "", fmt.Errorf("could not find Qobuz bundle script")
}
bundle, err := fetchText(ctx, hc, "https://play.qobuz.com"+match[1])
if err != nil {
return "", err
}
appIDRe := regexp.MustCompile(`production:{api:{appId:"(\d{9})"`)
appMatch := appIDRe.FindStringSubmatch(bundle)
if len(appMatch) < 2 {
return "", fmt.Errorf("could not parse Qobuz app id from bundle")
}
return appMatch[1], nil
}
func fetchText(ctx context.Context, hc *http.Client, rawURL string) (string, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil)
if err != nil {
return "", err
}
req.Header.Set("User-Agent", userAgent)
resp, err := hc.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode >= 300 {
return "", fmt.Errorf("%s: status %d", rawURL, resp.StatusCode)
}
data, err := io.ReadAll(io.LimitReader(resp.Body, 16<<20))
if err != nil {
return "", err
}
return string(data), nil
}
// SearchAlbums searches Qobuz albums.
func (c *Client) SearchAlbums(ctx context.Context, query string, limit int) ([]model.QobuzAlbum, error) {
if limit <= 0 {
limit = 10
}
params := url.Values{}
params.Set("query", query)
params.Set("limit", strconv.Itoa(limit))
var resp searchResponse
if err := c.get(ctx, "/album/search", params, &resp); err != nil {
return nil, err
}
albums := make([]model.QobuzAlbum, 0, len(resp.Albums.Items))
for _, item := range resp.Albums.Items {
album := model.QobuzAlbum{
ID: strings.TrimSpace(item.ID),
Title: strings.TrimSpace(item.Title),
Artist: strings.TrimSpace(item.Artist.Name),
UPC: strings.TrimSpace(item.UPC),
Year: yearFromDate(item.ReleaseDateOriginal),
TrackCount: item.TracksCount,
BitDepth: item.MaximumBitDepth,
SampleRate: item.MaximumSamplingRate,
}
if album.ID != "" && album.Title != "" {
albums = append(albums, album)
}
}
return albums, nil
}
// GetAlbum fetches one album including its track list and ISRCs.
func (c *Client) GetAlbum(ctx context.Context, albumID string) (*model.QobuzAlbum, error) {
params := url.Values{}
params.Set("album_id", albumID)
var resp albumResponse
if err := c.get(ctx, "/album/get", params, &resp); err != nil {
return nil, err
}
album := &model.QobuzAlbum{
ID: strings.TrimSpace(resp.ID),
Title: strings.TrimSpace(resp.Title),
Artist: strings.TrimSpace(resp.Artist.Name),
UPC: strings.TrimSpace(resp.UPC),
Year: yearFromDate(resp.ReleaseDateOriginal),
TrackCount: resp.TracksCount,
BitDepth: resp.MaximumBitDepth,
SampleRate: resp.MaximumSamplingRate,
}
for _, t := range resp.Tracks.Items {
album.Tracks = append(album.Tracks, model.QobuzTrack{
ID: t.ID,
Title: strings.TrimSpace(t.Title),
ISRC: strings.ToUpper(strings.TrimSpace(t.ISRC)),
TrackNumber: t.TrackNumber,
DiscNumber: t.MediaNumber,
Duration: t.Duration,
})
}
return album, nil
}
func yearFromDate(date string) int {
date = strings.TrimSpace(date)
if len(date) < 4 {
return 0
}
year, err := strconv.Atoi(date[:4])
if err != nil {
return 0
}
return year
}
func (c *Client) get(ctx context.Context, path string, params url.Values, out any) error {
if c.appID == "" {
return fmt.Errorf("qobuz app id is empty")
}
params.Set("app_id", c.appID)
endpoint := c.apiBase + path + "?" + params.Encode()
var lastErr error
for attempt := 1; attempt <= 4; attempt++ {
if err := c.wait(ctx); err != nil {
return err
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
if err != nil {
return err
}
req.Header.Set("User-Agent", userAgent)
req.Header.Set("X-App-Id", c.appID)
resp, err := c.http.Do(req)
if err != nil {
lastErr = err
sleep(ctx, time.Duration(attempt)*500*time.Millisecond)
continue
}
if resp.StatusCode == http.StatusTooManyRequests || resp.StatusCode >= 500 {
_ = resp.Body.Close()
lastErr = fmt.Errorf("qobuz api status %d", resp.StatusCode)
sleep(ctx, time.Duration(attempt)*time.Second)
continue
}
if resp.StatusCode >= 300 {
body, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
_ = resp.Body.Close()
return fmt.Errorf("qobuz api error (%d): %s", resp.StatusCode, strings.TrimSpace(string(body)))
}
if err := json.NewDecoder(resp.Body).Decode(out); err != nil {
_ = resp.Body.Close()
return err
}
_ = resp.Body.Close()
return nil
}
if lastErr == nil {
lastErr = fmt.Errorf("qobuz request failed after retries")
}
return lastErr
}
func (c *Client) wait(ctx context.Context) error {
c.mu.Lock()
now := time.Now()
wait := time.Duration(0)
if now.Before(c.next) {
wait = c.next.Sub(now)
c.next = c.next.Add(c.minDelay)
} else {
c.next = now.Add(c.minDelay)
}
c.mu.Unlock()
if wait > 0 {
sleep(ctx, wait)
}
return ctx.Err()
}
func sleep(ctx context.Context, d time.Duration) {
timer := time.NewTimer(d)
defer timer.Stop()
select {
case <-ctx.Done():
case <-timer.C:
}
}
type searchResponse struct {
Albums struct {
Items []searchAlbum `json:"items"`
Total int `json:"total"`
} `json:"albums"`
}
type searchAlbum struct {
ID string `json:"id"`
Title string `json:"title"`
Artist artist `json:"artist"`
Year int `json:"year"`
TracksCount int `json:"tracks_count"`
UPC string `json:"upc"`
ReleaseDateOriginal string `json:"release_date_original"`
MaximumBitDepth int `json:"maximum_bit_depth"`
MaximumSamplingRate float64 `json:"maximum_sampling_rate"`
}
type albumResponse struct {
ID string `json:"id"`
Title string `json:"title"`
Artist artist `json:"artist"`
UPC string `json:"upc"`
ReleaseDateOriginal string `json:"release_date_original"`
TracksCount int `json:"tracks_count"`
MaximumBitDepth int `json:"maximum_bit_depth"`
MaximumSamplingRate float64 `json:"maximum_sampling_rate"`
Tracks struct {
Items []struct {
ID int64 `json:"id"`
Title string `json:"title"`
TrackNumber int `json:"track_number"`
MediaNumber int `json:"media_number"`
ISRC string `json:"isrc"`
Duration int `json:"duration"`
} `json:"items"`
} `json:"tracks"`
}
type artist struct {
Name string `json:"name"`
}