Files
NovaSonic/backend/spotify_resolve.py
T
HoneyandClaude Sonnet 4.6 a401c7a607 fix: use Public().song_info() for tracks, Public().album_info() for albums
Both are the correct unauthenticated API methods on the Public class.
Song class requires a logged-in session and has no public equivalent.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-13 01:36:33 +02:00

192 lines
8.9 KiB
Python

#!/usr/bin/env python3
"""
Resolves Spotify URLs via the Spotify partner GraphQL API (api-partner.spotify.com).
This is the same internal API the Spotify web player uses — separate rate-limit bucket
from the public api.spotify.com/v1/ which gets throttled on server IPs.
"""
import sys, json, re, time
def eprint(*a): print(*a, file=sys.stderr)
# ─── RESPONSE PARSING ────────────────────────────────────────────────────────
# Partner API track items look like:
# { "itemV2": { "data": { "trackUnion": { "name":…, "artists":…, "albumOfTrack":…,
# "duration":…, "trackNumber":…, "contentRating":… } } } }
def _parse_track(item, default_album='', default_art='', default_artist=''):
try:
inner = (item.get('itemV2') or item.get('track') or {}).get('data') or {}
t = inner.get('trackUnion') or inner
if not t.get('name'): return None
artist_items = (t.get('artists') or {}).get('items') or []
artists = ', '.join(
a.get('profile', {}).get('name', '') for a in artist_items
) or default_artist
alb = t.get('albumOfTrack') or {}
alb_name = alb.get('name', '') or default_album
alb_imgs = (alb.get('images') or {}).get('items') or []
art = alb_imgs[0].get('url', '') if alb_imgs else default_art
release = ((alb.get('date') or {}).get('isoString') or '')[:10]
dur_ms = (t.get('duration') or {}).get('totalMilliseconds')
rating = (t.get('contentRating') or {}).get('label', '')
return {
'trackName': t.get('name', ''),
'artistName': artists,
'collectionName': alb_name,
'artworkUrl100': art,
'releaseDate': release,
'trackNumber': t.get('trackNumber'),
'trackExplicitness': 'explicit' if rating == 'EXPLICIT' else 'notExplicit',
'durationMs': dur_ms,
}
except Exception as e:
eprint(f'[parse] error on item: {e}')
return None
def _parse_images(imgs_obj):
items = (imgs_obj or {}).get('items') or []
return items[0].get('url', '') if items else ''
# ─── RESOLVER ────────────────────────────────────────────────────────────────
def _spotapi_classes():
import spotapi as _sp
available = [x for x in dir(_sp) if not x.startswith('_')]
eprint(f'[spotapi] exports: {available}')
return _sp, available
def resolve(sp_type, sp_id):
sp_mod, available = _spotapi_classes()
url = f'https://open.spotify.com/{sp_type}/{sp_id}'
if sp_type == 'track':
raw = sp_mod.Public().song_info(url)
eprint(f'[spotapi] track raw type={type(raw).__name__} keys={list(raw.keys()) if isinstance(raw, dict) else "?"}')
if isinstance(raw, dict):
for k, v in raw.items():
eprint(f'[spotapi] track[{k!r}] = {repr(v)[:160]}')
d = (raw.get('data') or {}) if isinstance(raw, dict) else {}
tu = d.get('trackUnion') or d
tr = _parse_track({'itemV2': {'data': {'trackUnion': tu}}}) or {
'trackName': raw.get('name', ''),
'artistName': raw.get('artist', ''),
'collectionName': raw.get('album', ''),
'artworkUrl100': raw.get('image', ''),
'releaseDate': raw.get('release_date', ''),
'trackNumber': raw.get('track_number'),
'trackExplicitness': 'notExplicit',
'durationMs': raw.get('duration_ms'),
}
return {'type': 'track', 'name': tr.get('trackName', ''),
'artist': tr.get('artistName', ''), 'artworkUrl': tr.get('artworkUrl100', ''),
'tracks': [tr]}
if sp_type == 'album':
alb_info = sp_mod.Public().album_info(url)
eprint(f'[spotapi] album raw type={type(alb_info).__name__} keys={list(alb_info.keys()) if isinstance(alb_info, dict) else "?"}')
if isinstance(alb_info, dict):
for k, v in alb_info.items():
eprint(f'[spotapi] alb[{k!r}] = {repr(v)[:160]}')
# Partner API: data.albumUnion.{name, artists, coverArt, tracks.items[]}
d = (alb_info.get('data') or {}) if isinstance(alb_info, dict) else {}
au = d.get('albumUnion') or d.get('albumV2') or (alb_info if isinstance(alb_info, dict) else {})
name = au.get('name', '')
# artist(s)
artist_items = (au.get('artists') or {}).get('items') or []
artist = ', '.join(
(a.get('profile') or {}).get('name', '') or a.get('name', '') for a in artist_items
) or au.get('artist', '')
# artwork
cover_items = (au.get('coverArt') or {}).get('sources') or (au.get('images') or {}).get('items') or []
art = cover_items[0].get('url', '') if cover_items else ''
# tracks
raw_tracks = (au.get('tracks') or {}).get('items') or []
eprint(f'[spotapi] album tracks count={len(raw_tracks)} first={repr(raw_tracks[0])[:200] if raw_tracks else "none"}')
# album track items: {uid, track: {__typename, data: {trackUnion: {...}}}}
# wrap as {itemV2: track_obj} so _parse_track can navigate itemV2.data.trackUnion
def _alb_track(item):
track_obj = item.get('track') or item
return _parse_track({'itemV2': track_obj},
default_album=name, default_art=art,
default_artist=artist)
tracks = [t for t in (_alb_track(i) for i in raw_tracks) if t]
eprint(f'[spotapi] album ok — {len(tracks)} tracks')
return {'type': 'album', 'name': name, 'artist': artist, 'artworkUrl': art, 'tracks': tracks}
# playlist
cls_name = next((n for n in ('PublicPlaylist', 'Playlist') if n in available), None)
if not cls_name:
raise Exception(f'spotapi has no playlist class (available: {available})')
pl = getattr(sp_mod, cls_name)(url)
def _pl_items(page):
"""Extract items list from partner API response: data.playlistV2.content.items"""
if isinstance(page, list): return page
d = page.get('data') or {}
pl2 = d.get('playlistV2') or {}
content = pl2.get('content') or {}
return content.get('items') or page.get('items') or page.get('tracks') or []
def _pl_meta(page):
"""Extract playlist metadata from partner API response"""
if not isinstance(page, dict): return {}, {}, []
d = page.get('data') or {}
pl2 = d.get('playlistV2') or {}
attrs = pl2.get('attributes') or pl2
owner_obj = pl2.get('ownerV2') or pl2.get('owner') or {}
owner_data = owner_obj.get('data') or owner_obj
imgs = (pl2.get('images') or {}).get('items') or []
return attrs, owner_data, imgs
tracks, skipped, offset = [], 0, 0
first_page = None
while True:
page = pl.get_playlist_info(limit=100, offset=offset)
if first_page is None: first_page = page
items = _pl_items(page)
if not items: break
for item in items:
typename = (item.get('itemV2') or {}).get('data', {}).get('__typename', '')
if typename == 'LocalTrackResponseWrapper':
skipped += 1; continue
tr = _parse_track(item)
if tr: tracks.append(tr)
if len(items) < 100: break
offset += len(items)
time.sleep(0.3)
attrs, owner_data, imgs = _pl_meta(first_page or {})
name = attrs.get('name', '') or attrs.get('title', '')
owner = owner_data.get('name', '') or owner_data.get('displayName', '')
art = imgs[0].get('url', '') if imgs else ''
eprint(f'[spotapi] playlist ok — {len(tracks)} tracks')
return {'type': 'playlist', 'name': name, 'artist': owner,
'artworkUrl': art, 'skippedLocal': skipped, 'tracks': tracks}
# ─── MAIN ────────────────────────────────────────────────────────────────────
def main():
if len(sys.argv) < 2: eprint('No URL'); sys.exit(1)
url = sys.argv[1]
m = re.search(r'open\.spotify\.com/(?:.*/)?(track|album|playlist)/([A-Za-z0-9]+)', url)
if not m: eprint('Invalid URL'); sys.exit(1)
sp_type, sp_id = m.group(1), m.group(2)
eprint(f'[spotify] resolving {sp_type} {sp_id}')
try:
result = resolve(sp_type, sp_id)
print(json.dumps(result, ensure_ascii=False))
except SystemExit: raise
except Exception as e:
eprint(f'[spotapi] failed: {type(e).__name__}: {e}')
sys.exit(1)
if __name__ == '__main__':
try: main()
except SystemExit: raise
except Exception as e: eprint(f'fatal: {e}'); sys.exit(1)