fix: detect spotapi exports at runtime, lazy-import per type

PublicSong doesn't exist in the installed spotapi version. Now discovers
available class names at startup and picks the right one dynamically.
Missing track/album class no longer breaks playlist resolution.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
HoneyandClaude Sonnet 4.6 committed 2026-05-12 21:11:06 +02:00
1 parent 4ec441af57
commit ddc6cb8cb2
1 file changed
+31 -27
+31 -27
View File
@@ -53,19 +53,24 @@ def _parse_images(imgs_obj):
# ─── RESOLVER ──────────────────────────────────────────────────────────────── # ─── RESOLVER ────────────────────────────────────────────────────────────────
def resolve(sp_type, sp_id): def _spotapi_classes():
from spotapi import PublicPlaylist, PublicAlbum, PublicSong 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}' url = f'https://open.spotify.com/{sp_type}/{sp_id}'
if sp_type == 'track': if sp_type == 'track':
song = PublicSong(url) cls_name = next((n for n in ('PublicSong', 'Song', 'PublicTrack', 'Track') if n in available), None)
if not cls_name:
raise Exception(f'spotapi has no track class (available: {available})')
song = getattr(sp_mod, cls_name)(url)
raw = song.get_song_info() raw = song.get_song_info()
eprint(f'[spotapi] track response keys: {list(raw.keys()) if isinstance(raw, dict) else type(raw)}') eprint(f'[spotapi] track raw keys: {list(raw.keys()) if isinstance(raw, dict) else type(raw)}')
tr = _parse_track(raw) tr = _parse_track(raw) or {
if not tr:
# Fallback: raw might already be a flat dict
tr = {
'trackName': raw.get('name', ''), 'trackName': raw.get('name', ''),
'artistName': raw.get('artist', ''), 'artistName': raw.get('artist', ''),
'collectionName': raw.get('album', ''), 'collectionName': raw.get('album', ''),
@@ -75,40 +80,42 @@ def resolve(sp_type, sp_id):
'trackExplicitness': 'notExplicit', 'trackExplicitness': 'notExplicit',
'durationMs': raw.get('duration_ms'), 'durationMs': raw.get('duration_ms'),
} }
name = tr.get('trackName', '') return {'type': 'track', 'name': tr.get('trackName', ''),
artist = tr.get('artistName', '') 'artist': tr.get('artistName', ''), 'artworkUrl': tr.get('artworkUrl100', ''),
art = tr.get('artworkUrl100', '') 'tracks': [tr]}
return {'type': 'track', 'name': name, 'artist': artist, 'artworkUrl': art, 'tracks': [tr]}
if sp_type == 'album': if sp_type == 'album':
alb = PublicAlbum(url) cls_name = next((n for n in ('PublicAlbum', 'Album') if n in available), None)
if not cls_name:
raise Exception(f'spotapi has no album class (available: {available})')
alb = getattr(sp_mod, cls_name)(url)
alb_info = alb.get_album_info() alb_info = alb.get_album_info()
eprint(f'[spotapi] album response type: {type(alb_info)}, keys: {list(alb_info.keys()) if isinstance(alb_info, dict) else "?"}') eprint(f'[spotapi] album raw type={type(alb_info).__name__} keys={list(alb_info.keys()) if isinstance(alb_info, dict) else "?"}')
# alb_info may be a dict with metadata + items, or just items
meta = alb_info if isinstance(alb_info, dict) else {} meta = alb_info if isinstance(alb_info, dict) else {}
name = meta.get('name', '') name = meta.get('name', '')
artist = meta.get('artist', '') or meta.get('artists', '') artist = meta.get('artist', '') or meta.get('artists', '')
art = meta.get('image', '') or meta.get('cover', '') art = meta.get('image', '') or meta.get('cover', '')
raw_tracks = meta.get('tracks') or meta.get('items') or (alb_info if isinstance(alb_info, list) else []) raw_tracks = meta.get('tracks') or meta.get('items') or (alb_info if isinstance(alb_info, list) else [])
tracks = [t for t in (_parse_track(i) for i in raw_tracks) if t] tracks = [t for t in (_parse_track(i) for i in raw_tracks) if t]
eprint(f'[spotapi] album ok — {len(tracks)} tracks') eprint(f'[spotapi] album ok — {len(tracks)} tracks')
return {'type': 'album', 'name': name, 'artist': artist, 'artworkUrl': art, 'tracks': tracks} return {'type': 'album', 'name': name, 'artist': artist, 'artworkUrl': art, 'tracks': tracks}
# playlist # playlist
pl = PublicPlaylist(url) cls_name = next((n for n in ('PublicPlaylist', 'Playlist') if n in available), None)
pl_meta = pl.get_playlist_info(limit=1) # first call often returns metadata too if not cls_name:
eprint(f'[spotapi] playlist meta type: {type(pl_meta)}') raise Exception(f'spotapi has no playlist class (available: {available})')
pl = getattr(sp_mod, cls_name)(url)
pl_meta = pl.get_playlist_info(limit=1)
eprint(f'[spotapi] playlist first-page type={type(pl_meta).__name__}')
tracks, skipped = [], 0 tracks, skipped, offset = [], 0, 0
offset = 0
while True: while True:
page = pl.get_playlist_info(limit=100, offset=offset) page = pl.get_playlist_info(limit=100, offset=offset)
items = page if isinstance(page, list) else (page.get('items') or page.get('tracks') or []) items = page if isinstance(page, list) else (page.get('items') or page.get('tracks') or [])
if not items: break if not items: break
for item in items: for item in items:
if (item.get('itemV2') or item.get('track', {}).get('data', {})).get('__typename') == 'LocalTrackResponseWrapper': typename = (item.get('itemV2') or {}).get('data', {}).get('__typename', '')
if typename == 'LocalTrackResponseWrapper':
skipped += 1; continue skipped += 1; continue
tr = _parse_track(item) tr = _parse_track(item)
if tr: tracks.append(tr) if tr: tracks.append(tr)
@@ -116,10 +123,7 @@ def resolve(sp_type, sp_id):
offset += len(items) offset += len(items)
time.sleep(0.3) time.sleep(0.3)
# Extract playlist name/art from first page if available name = owner = art = ''
name = ''
owner = ''
art = ''
if isinstance(pl_meta, dict): if isinstance(pl_meta, dict):
name = pl_meta.get('name', '') name = pl_meta.get('name', '')
owner = pl_meta.get('owner', '') or pl_meta.get('owner_name', '') owner = pl_meta.get('owner', '') or pl_meta.get('owner_name', '')