344 lines
8.8 KiB
Go
344 lines
8.8 KiB
Go
// Package apple talks to the public Apple Music catalog API. It scrapes a web
|
|
// player token (no Apple ID/login) and fetches playlists plus album metadata.
|
|
package apple
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"net/url"
|
|
"strconv"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
"applesync/internal/model"
|
|
)
|
|
|
|
const defaultAPIBase = "https://amp-api.music.apple.com"
|
|
|
|
type Client struct {
|
|
http *http.Client
|
|
language string
|
|
apiBase string
|
|
|
|
mu sync.Mutex
|
|
token string
|
|
|
|
logf func(string, ...any)
|
|
}
|
|
|
|
func NewClient(language string) *Client {
|
|
if strings.TrimSpace(language) == "" {
|
|
language = "en-US"
|
|
}
|
|
return &Client{
|
|
http: &http.Client{Timeout: 30 * time.Second},
|
|
language: language,
|
|
apiBase: defaultAPIBase,
|
|
}
|
|
}
|
|
|
|
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...)
|
|
}
|
|
}
|
|
|
|
func (c *Client) EnsureToken(ctx context.Context) error {
|
|
c.mu.Lock()
|
|
defer c.mu.Unlock()
|
|
if strings.TrimSpace(c.token) != "" {
|
|
return nil
|
|
}
|
|
token, err := FetchWebToken(ctx, c.http)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
c.token = token
|
|
c.log("apple: web token acquired")
|
|
return nil
|
|
}
|
|
|
|
func (c *Client) refreshToken(ctx context.Context) error {
|
|
token, err := FetchWebToken(ctx, c.http)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
c.mu.Lock()
|
|
c.token = token
|
|
c.mu.Unlock()
|
|
c.log("apple: web token refreshed")
|
|
return nil
|
|
}
|
|
|
|
func (c *Client) currentToken() string {
|
|
c.mu.Lock()
|
|
defer c.mu.Unlock()
|
|
return c.token
|
|
}
|
|
|
|
// FetchPlaylist fetches a public playlist, following pagination.
|
|
func (c *Client) FetchPlaylist(ctx context.Context, ref PlaylistRef) (*model.Playlist, error) {
|
|
endpoint := fmt.Sprintf("%s/v1/catalog/%s/playlists/%s", c.apiBase, url.PathEscape(ref.Storefront), url.PathEscape(ref.PlaylistID))
|
|
q := url.Values{}
|
|
q.Set("omit[resource]", "autos")
|
|
q.Set("include", "tracks")
|
|
q.Set("l", c.language)
|
|
|
|
var first playlistResponse
|
|
if err := c.getJSON(ctx, endpoint+"?"+q.Encode(), &first); err != nil {
|
|
return nil, err
|
|
}
|
|
if len(first.Data) == 0 {
|
|
return nil, fmt.Errorf("apple playlist response missing data")
|
|
}
|
|
|
|
item := first.Data[0]
|
|
pl := &model.Playlist{
|
|
URL: ref.RawURL,
|
|
SourceID: item.ID,
|
|
Storefront: ref.Storefront,
|
|
Name: strings.TrimSpace(item.Attributes.Name),
|
|
}
|
|
for _, t := range item.Relationships.Tracks.Data {
|
|
pl.Tracks = append(pl.Tracks, toTrack(t))
|
|
}
|
|
c.log("apple: playlist %q: %d tracks", pl.Name, len(pl.Tracks))
|
|
|
|
next := strings.TrimSpace(item.Relationships.Tracks.Next)
|
|
for next != "" {
|
|
nextURL := next
|
|
if strings.HasPrefix(nextURL, "/") {
|
|
nextURL = c.apiBase + nextURL
|
|
}
|
|
var page trackPage
|
|
if err := c.getJSON(ctx, nextURL, &page); err != nil {
|
|
return nil, err
|
|
}
|
|
for _, t := range page.Data {
|
|
pl.Tracks = append(pl.Tracks, toTrack(t))
|
|
}
|
|
next = strings.TrimSpace(page.Next)
|
|
}
|
|
c.log("apple: playlist %q: fetched %d tracks", pl.Name, len(pl.Tracks))
|
|
if len(pl.Tracks) == 0 {
|
|
return nil, fmt.Errorf("apple playlist %q has no tracks", pl.Name)
|
|
}
|
|
return pl, nil
|
|
}
|
|
|
|
// EnrichAlbums batches the playlist tracks through the songs endpoint with
|
|
// include=albums. This is where album ids, UPCs, album artists and release
|
|
// dates come from; the playlist's own track list only carries album names.
|
|
func (c *Client) EnrichAlbums(ctx context.Context, pl *model.Playlist) error {
|
|
if len(pl.Tracks) == 0 {
|
|
return nil
|
|
}
|
|
byID := make(map[string]songItem, len(pl.Tracks))
|
|
ids := make([]string, 0, len(pl.Tracks))
|
|
for _, track := range pl.Tracks {
|
|
if track.AppleID != "" {
|
|
ids = append(ids, track.AppleID)
|
|
}
|
|
}
|
|
for start := 0; start < len(ids); start += 100 {
|
|
end := start + 100
|
|
if end > len(ids) {
|
|
end = len(ids)
|
|
}
|
|
q := url.Values{}
|
|
q.Set("ids", strings.Join(ids[start:end], ","))
|
|
q.Set("include", "albums")
|
|
q.Set("l", c.language)
|
|
endpoint := fmt.Sprintf("%s/v1/catalog/%s/songs?%s", c.apiBase, url.PathEscape(pl.Storefront), q.Encode())
|
|
var resp songsResponse
|
|
if err := c.getJSON(ctx, endpoint, &resp); err != nil {
|
|
return err
|
|
}
|
|
for _, song := range resp.Data {
|
|
byID[song.ID] = song
|
|
}
|
|
}
|
|
|
|
albumIndex := map[string]*model.Album{}
|
|
albumOrder := make([]*model.Album, 0, len(pl.Tracks))
|
|
missingAlbums := 0
|
|
for _, track := range pl.Tracks {
|
|
song, ok := byID[track.AppleID]
|
|
if ok {
|
|
mergeSong(track, song)
|
|
}
|
|
if track.AlbumID == "" {
|
|
missingAlbums++
|
|
continue
|
|
}
|
|
album, seen := albumIndex[track.AlbumID]
|
|
if !seen {
|
|
artist := track.AlbumArtist
|
|
if artist == "" {
|
|
artist = track.ArtistName
|
|
}
|
|
album = &model.Album{
|
|
AppleID: track.AlbumID,
|
|
Title: track.AlbumName,
|
|
Artist: artist,
|
|
UPC: track.AlbumUPC,
|
|
TrackCount: track.AlbumTrackCount,
|
|
ReleaseDate: track.AlbumReleaseDate,
|
|
}
|
|
if len(track.AlbumReleaseDate) >= 4 {
|
|
if year, err := strconv.Atoi(track.AlbumReleaseDate[:4]); err == nil {
|
|
album.Year = year
|
|
}
|
|
}
|
|
albumIndex[track.AlbumID] = album
|
|
albumOrder = append(albumOrder, album)
|
|
}
|
|
album.Tracks = append(album.Tracks, track)
|
|
}
|
|
pl.Albums = albumOrder
|
|
if missingAlbums > 0 {
|
|
c.log("apple: warning: %d playlist tracks have no album relationship", missingAlbums)
|
|
}
|
|
c.log("apple: playlist %q: %d unique albums", pl.Name, len(pl.Albums))
|
|
return nil
|
|
}
|
|
|
|
func toTrack(t playlistTrack) *model.Track {
|
|
at := t.Attributes
|
|
track := &model.Track{
|
|
AppleID: strings.TrimSpace(t.ID),
|
|
Title: strings.TrimSpace(at.Name),
|
|
ArtistName: strings.TrimSpace(at.ArtistName),
|
|
AlbumName: strings.TrimSpace(at.AlbumName),
|
|
ISRC: strings.ToUpper(strings.TrimSpace(at.ISRC)),
|
|
DurationMS: at.DurationInMillis,
|
|
TrackNumber: at.TrackNumber,
|
|
DiscNumber: at.DiscNumber,
|
|
Explicit: strings.EqualFold(strings.TrimSpace(at.ContentRating), "explicit"),
|
|
}
|
|
if track.ArtistName != "" {
|
|
track.Artists = []string{track.ArtistName}
|
|
}
|
|
for _, album := range t.Relationships.Albums.Data {
|
|
if album.ID != "" {
|
|
track.AlbumID = album.ID
|
|
break
|
|
}
|
|
}
|
|
return track
|
|
}
|
|
|
|
// mergeSong fills in fields that are only available from the songs endpoint.
|
|
func mergeSong(track *model.Track, song songItem) {
|
|
at := song.Attributes
|
|
if at.Name != "" {
|
|
track.Title = strings.TrimSpace(at.Name)
|
|
}
|
|
if at.ArtistName != "" {
|
|
track.ArtistName = strings.TrimSpace(at.ArtistName)
|
|
track.Artists = []string{track.ArtistName}
|
|
}
|
|
if at.AlbumName != "" {
|
|
track.AlbumName = strings.TrimSpace(at.AlbumName)
|
|
}
|
|
if at.ISRC != "" {
|
|
track.ISRC = strings.ToUpper(strings.TrimSpace(at.ISRC))
|
|
}
|
|
if at.DurationInMillis > 0 {
|
|
track.DurationMS = at.DurationInMillis
|
|
}
|
|
if at.TrackNumber > 0 {
|
|
track.TrackNumber = at.TrackNumber
|
|
}
|
|
if at.DiscNumber > 0 {
|
|
track.DiscNumber = at.DiscNumber
|
|
}
|
|
track.Explicit = strings.EqualFold(strings.TrimSpace(at.ContentRating), "explicit")
|
|
|
|
for _, album := range song.Relationships.Albums.Data {
|
|
if album.ID == "" {
|
|
continue
|
|
}
|
|
track.AlbumID = album.ID
|
|
aa := album.Attributes
|
|
if aa.Name != "" {
|
|
track.AlbumName = strings.TrimSpace(aa.Name)
|
|
}
|
|
if aa.ArtistName != "" {
|
|
track.AlbumArtist = strings.TrimSpace(aa.ArtistName)
|
|
}
|
|
track.AlbumUPC = strings.TrimSpace(aa.UPC)
|
|
track.AlbumTrackCount = aa.TrackCount
|
|
track.AlbumReleaseDate = strings.TrimSpace(aa.ReleaseDate)
|
|
break
|
|
}
|
|
}
|
|
|
|
func (c *Client) getJSON(ctx context.Context, endpoint string, out any) error {
|
|
if err := c.EnsureToken(ctx); err != nil {
|
|
return err
|
|
}
|
|
allowRefresh := true
|
|
var lastErr error
|
|
for attempt := 1; attempt <= 4; attempt++ {
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
req.Header.Set("Authorization", "Bearer "+c.currentToken())
|
|
req.Header.Set("Origin", "https://music.apple.com")
|
|
req.Header.Set("User-Agent", browserUA)
|
|
|
|
resp, err := c.http.Do(req)
|
|
if err != nil {
|
|
lastErr = err
|
|
sleep(ctx, time.Duration(attempt)*500*time.Millisecond)
|
|
continue
|
|
}
|
|
|
|
if resp.StatusCode == http.StatusUnauthorized && allowRefresh {
|
|
_ = resp.Body.Close()
|
|
allowRefresh = false
|
|
if err := c.refreshToken(ctx); err != nil {
|
|
return fmt.Errorf("apple token refresh failed: %w", err)
|
|
}
|
|
continue
|
|
}
|
|
if resp.StatusCode == http.StatusTooManyRequests || resp.StatusCode >= 500 {
|
|
_ = resp.Body.Close()
|
|
lastErr = fmt.Errorf("apple 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("apple api error (%d): %s", resp.StatusCode, strings.TrimSpace(string(body)))
|
|
}
|
|
defer resp.Body.Close()
|
|
if err := json.NewDecoder(resp.Body).Decode(out); err != nil {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
if lastErr == nil {
|
|
lastErr = fmt.Errorf("apple request failed after retries")
|
|
}
|
|
return lastErr
|
|
}
|
|
|
|
func sleep(ctx context.Context, d time.Duration) {
|
|
timer := time.NewTimer(d)
|
|
defer timer.Stop()
|
|
select {
|
|
case <-ctx.Done():
|
|
case <-timer.C:
|
|
}
|
|
}
|