JSON-LD could set track_name but return empty byArtist, making the OG block (guarded by `if not track_name`) never run — leaving artist blank. Now OG runs whenever either name or artist is missing, and only fills fields that are still empty so JSON-LD name isn't overwritten. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
269 lines
13 KiB
Python
269 lines
13 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, html as _html, urllib.request
|
|
|
|
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':
|
|
pub = sp_mod.Public()
|
|
tr = None
|
|
# Try partner API first (works for some tracks)
|
|
for arg in [f'spotify:track:{sp_id}', url]:
|
|
try:
|
|
r = pub.song_info(arg)
|
|
tu_type = ((r.get('data') or {}).get('trackUnion') or {}).get('__typename', '')
|
|
if tu_type == 'GenericError':
|
|
eprint(f'[spotapi] song_info({arg!r}) → GenericError')
|
|
continue
|
|
d = (r.get('data') or {})
|
|
tu = d.get('trackUnion') or d
|
|
tr = _parse_track({'itemV2': {'data': {'trackUnion': tu}}})
|
|
if tr and tr.get('trackName'):
|
|
eprint(f'[spotapi] track resolved via song_info')
|
|
break
|
|
tr = None
|
|
except Exception as e:
|
|
eprint(f'[spotapi] song_info({arg!r}) failed: {e}')
|
|
|
|
# Fallback: scrape the public Spotify track page
|
|
if not tr:
|
|
eprint(f'[spotapi] falling back to page scrape for track {sp_id}')
|
|
try:
|
|
req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
|
|
with urllib.request.urlopen(req, timeout=10) as resp:
|
|
page = resp.read().decode('utf-8', errors='replace')
|
|
|
|
track_name, artist_name, album_name, art_url = '', '', '', ''
|
|
|
|
# 1) JSON-LD structured data — most reliable, always has byArtist
|
|
ld_m = re.search(r'<script[^>]+type=["\']application/ld\+json["\'][^>]*>(.*?)</script>', page, re.DOTALL | re.IGNORECASE)
|
|
if ld_m:
|
|
try:
|
|
ld = json.loads(ld_m.group(1))
|
|
track_name = ld.get('name', '')
|
|
by_artist = ld.get('byArtist', [])
|
|
if isinstance(by_artist, list):
|
|
artist_name = ', '.join(a.get('name', '') for a in by_artist if a.get('name'))
|
|
elif isinstance(by_artist, dict):
|
|
artist_name = by_artist.get('name', '')
|
|
in_album = ld.get('inAlbum') or {}
|
|
album_name = in_album.get('name', '') if isinstance(in_album, dict) else ''
|
|
eprint(f'[spotapi] JSON-LD: name={track_name!r} artist={artist_name!r} album={album_name!r}')
|
|
except Exception as e:
|
|
eprint(f'[spotapi] JSON-LD parse failed: {e}')
|
|
|
|
# 2) OG tags — fill in any fields still missing after JSON-LD
|
|
# Real format: "Artist · Song · Year" — artist is index 0
|
|
if not track_name or not artist_name:
|
|
og = {}
|
|
for m in re.finditer(r'<meta\s+(?:property|name)=["\']og:([^"\']+)["\']\s+content=["\']([^"\']*)["\']', page):
|
|
og[m.group(1)] = _html.unescape(m.group(2))
|
|
for m in re.finditer(r'<meta\s+content=["\']([^"\']*)["\'][^>]+(?:property|name)=["\']og:([^"\']+)["\']', page):
|
|
og[m.group(2)] = _html.unescape(m.group(1))
|
|
desc_parts = [p.strip() for p in og.get('description', '').split('·')]
|
|
if not track_name:
|
|
track_name = og.get('title', '')
|
|
if not artist_name:
|
|
artist_name = desc_parts[0] if desc_parts else ''
|
|
if not art_url:
|
|
art_url = og.get('image', '')
|
|
eprint(f'[spotapi] OG scrape: name={track_name!r} artist={artist_name!r}')
|
|
|
|
if track_name:
|
|
tr = {
|
|
'trackName': track_name,
|
|
'artistName': artist_name,
|
|
'collectionName': album_name,
|
|
'artworkUrl100': art_url,
|
|
'releaseDate': '',
|
|
'trackNumber': None,
|
|
'trackExplicitness': 'notExplicit',
|
|
'durationMs': None,
|
|
}
|
|
except Exception as e:
|
|
eprint(f'[spotapi] page scrape failed: {e}')
|
|
|
|
if not tr:
|
|
raise Exception(f'Track resolution failed: song_info returned GenericError and OG scrape found no title')
|
|
return {'type': 'track', 'name': tr.get('trackName', ''),
|
|
'artist': tr.get('artistName', ''), 'artworkUrl': tr.get('artworkUrl100', ''),
|
|
'tracks': [tr]}
|
|
|
|
if sp_type == 'album':
|
|
# PublicAlbum.get_album_info() → metadata (data.albumUnion.{name,artists,coverArt})
|
|
# Public().album_info(url) → generator that yields PAGES (lists of track dicts)
|
|
cls_name = next((n for n in ('PublicAlbum', 'Album') if n in available), None)
|
|
alb_meta = getattr(sp_mod, cls_name)(url).get_album_info() if cls_name else {}
|
|
d = (alb_meta.get('data') or {}) if isinstance(alb_meta, dict) else {}
|
|
au = d.get('albumUnion') or d.get('albumV2') or {}
|
|
name = au.get('name', '')
|
|
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
|
|
)
|
|
cover_items = (au.get('coverArt') or {}).get('sources') or []
|
|
art = cover_items[0].get('url', '') if cover_items else ''
|
|
|
|
# Flatten pages from the generator: each page is a list of track dicts
|
|
raw_tracks = [item for page in sp_mod.Public().album_info(url)
|
|
for item in (page if isinstance(page, list) else [page])]
|
|
eprint(f'[spotapi] album_info → {len(raw_tracks)} tracks; first={repr(raw_tracks[0])[:200] if raw_tracks else "none"}')
|
|
|
|
def _alb_track(item):
|
|
# Track items are flat: {track: {name, artists, contentRating, duration, trackNumber}}
|
|
t = item.get('track') or item
|
|
if not isinstance(t, dict): return None
|
|
artist_items2 = (t.get('artists') or {}).get('items') or []
|
|
artists = ', '.join(
|
|
(a.get('profile') or {}).get('name', '') for a in artist_items2
|
|
) or artist
|
|
dur_ms = (t.get('duration') or {}).get('totalMilliseconds')
|
|
rating = (t.get('contentRating') or {}).get('label', '')
|
|
track_name = t.get('name', '')
|
|
if not track_name: return None
|
|
return {
|
|
'trackName': track_name,
|
|
'artistName': artists,
|
|
'collectionName': name,
|
|
'artworkUrl100': art,
|
|
'releaseDate': '',
|
|
'trackNumber': t.get('trackNumber'),
|
|
'trackExplicitness': 'explicit' if rating == 'EXPLICIT' else 'notExplicit',
|
|
'durationMs': dur_ms,
|
|
}
|
|
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)
|