Files
spotify/tools/mock_server.py
Tamas Csikel 3a66e0c7c7
All checks were successful
release / release (push) Successful in 12m14s
Spotify for Fennec OS: native TV client
Rust + Slint on sf-ui's Liquid Glass, with the page engine of Netflex TV.
librespot plays (GStreamer on the TV) and makes the TV a Spotify Connect
device; the Web API (token from the session) feeds the pages.

- Sign-in with the phone: a pairing code / QR code (spotify.com/pair,
  OAuth device flow) or picking the TV in the Spotify app (zeroconf).
- Home, search, library, playlist / album / liked songs / podcast pages,
  artist pages, settings; the user's picture top right.
- Now playing: seek, shuffle, repeat, like, synced lyrics, queue.
- package.sh builds x86-64 and aarch64 (Raspberry Pi); the Gitea CI
  releases both on a tag.
- tools/mock_server.py and SPOTIFY_MOCK for work without an account.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 17:23:34 +01:00

172 lines
8.6 KiB
Python
Executable File

#!/usr/bin/env python3
"""Stand-in for the Spotify Web API (api.spotify.com/v1), for UI work and
screenshots without an account. Made-up data, pictures from picsum.photos.
python3 tools/mock_server.py --port 7890
SPOTIFY_MOCK=1 SPOTIFY_API=http://127.0.0.1:7890/v1 cargo run
SPOTIFY_MOCK=1 also replaces librespot (signed in at once, fake playback);
SPOTIFY_MOCK=signin shows the sign-in screen with a sample code.
"""
import argparse
import json
import re
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlparse
def img(seed, size=640):
return [{"url": f"https://picsum.photos/seed/{seed}/{size}/{size}", "width": size, "height": size},
{"url": f"https://picsum.photos/seed/{seed}/300/300", "width": 300, "height": 300}]
ARTISTS = ["Napfény Zenekar", "Éjféli Kék", "Hold Utca", "Kristóf Vass", "Lili és a Fények", "Déli Szél",
"Városi Zaj", "Mira", "Tisza Trió", "Galaxis", "Neon Hajnal", "Bori"]
WORDS = ["Hajnali", "Nyári", "Csendes", "Fényes", "Messzi", "Kék", "Arany", "Éjszakai", "Vad", "Puha", "Régi", "Új"]
NOUNS = ["fények", "utca", "tenger", "város", "dal", "álom", "szél", "eső", "tánc", "csillagok", "part", "hajó"]
def artist(i):
return {"id": f"ar{i}", "name": ARTISTS[i % len(ARTISTS)], "uri": f"spotify:artist:ar{i}", "type": "artist",
"images": img(f"artist{i}"), "followers": {"total": 12345 * (i + 3) * 17}, "genres": ["magyar pop", "indie"]}
def album(i):
return {"id": f"al{i}", "name": f"{WORDS[i % 12]} {NOUNS[(i * 5) % 12]}", "uri": f"spotify:album:al{i}",
"images": img(f"album{i}"), "artists": [{"id": f"ar{i % 12}", "name": ARTISTS[i % 12], "uri": f"spotify:artist:ar{i % 12}"}],
"release_date": f"{2010 + i % 15}-0{1 + i % 9}-1{i % 9}", "total_tracks": 10, "album_type": "album" if i % 3 else "single",
"label": "Fennec Records"}
def track(i, with_album=True):
a = album(i // 10)
t = {"id": f"tr{i}", "name": f"{WORDS[(i * 7) % 12]} {NOUNS[(i * 3) % 12]}", "uri": f"spotify:track:tr{i}", "type": "track",
"duration_ms": 150000 + (i * 7919) % 120000, "explicit": i % 7 == 0, "track_number": i % 10 + 1,
"artists": [{"id": f"ar{i % 12}", "name": ARTISTS[i % 12], "uri": f"spotify:artist:ar{i % 12}"}]}
if with_album:
t["album"] = a
return t
def playlist(i):
names = ["Reggeli kávé", "Edzés", "Esti nyugalom", "Road trip", "Fókusz", "Buli", "Magyar slágerek", "Discover Weekly",
"Release Radar", "Chill", "Gitáros", "Retro 80s"]
return {"id": f"pl{i}", "name": names[i % len(names)], "uri": f"spotify:playlist:pl{i}", "images": img(f"pl{i}"),
"description": "Válogatás <a href=\"x\">a legjobbakból</a> &amp; még több.", "owner": {"id": "demo" if i < 4 else "spotify",
"display_name": "Demó" if i < 4 else "Spotify"}, "tracks": {"total": 40}, "followers": {"total": 1200 * (i + 1)}}
def show(i):
names = ["Tudomány percek", "Zene és ember", "Esti mese", "Tech hírek", "Futás közben"]
return {"id": f"sh{i}", "name": names[i % 5], "uri": f"spotify:show:sh{i}", "images": img(f"show{i}"),
"publisher": "Fennec Podcast", "description": "Heti beszélgetések.", "total_episodes": 30}
def episode(i):
return {"id": f"ep{i}", "name": f"{i + 1}. rész: {WORDS[i % 12]} {NOUNS[i % 12]}", "uri": f"spotify:episode:ep{i}",
"type": "episode", "duration_ms": 1800000 + i * 60000, "release_date": f"2026-10-{1 + i % 28:02d}",
"images": img(f"ep{i}"), "description": "Egy epizód.", "resume_point": {"fully_played": i % 4 == 1, "resume_position_ms": 600000 if i % 4 == 2 else 0}}
def page(items, offset, limit, total, url):
nxt = f"{url}?offset={offset + limit}&limit={limit}" if offset + limit < total else None
return {"items": items, "offset": offset, "limit": limit, "total": total, "next": nxt}
class H(BaseHTTPRequestHandler):
def send_json(self, obj, code=200):
body = json.dumps(obj).encode()
self.send_response(code)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, fmt, *args):
pass
def do_PUT(self):
self.send_response(204)
self.end_headers()
do_DELETE = do_PUT
do_POST = do_PUT
def do_GET(self):
u = urlparse(self.path)
q = {k: v[0] for k, v in parse_qs(u.query).items()}
p = u.path.removeprefix("/v1")
off, lim = int(q.get("offset", 0)), int(q.get("limit", 20))
if p == "/me":
return self.send_json({"id": "demo", "display_name": "Demó Felhasználó", "product": "premium", "country": "HU", "images": img("me", 300)})
if p == "/me/player/recently-played":
return self.send_json({"items": [{"track": track(i * 3), "context": {"uri": f"spotify:album:al{i * 3 // 10}", "type": "album"}} for i in range(20)]})
if p == "/me/top/artists":
return self.send_json(page([artist(i) for i in range(12)], 0, 20, 12, p))
if p == "/me/top/tracks":
return self.send_json(page([track(i * 5) for i in range(15)], 0, 20, 15, p))
if p == "/browse/new-releases":
return self.send_json({"albums": page([album(i + 20) for i in range(15)], 0, 20, 15, p)})
if p == "/me/playlists":
return self.send_json(page([playlist(i) for i in range(off, min(off + 50, 12))], off, 50, 12, p))
if p == "/me/tracks":
total = 230
return self.send_json(page([{"track": track(i)} for i in range(off, min(off + lim, total))], off, lim, total, p))
if p == "/me/albums":
return self.send_json(page([{"album": album(i)} for i in range(off, min(off + 50, 18))], off, 50, 18, p))
if p == "/me/shows":
return self.send_json(page([{"show": show(i)} for i in range(5)], 0, 50, 5, p))
if p == "/me/following":
return self.send_json({"artists": {"items": [artist(i) for i in range(12)], "cursors": {"after": None}}})
if p.endswith("/contains"):
ids = q.get("ids", "x").split(",")
return self.send_json([i.endswith("1") for i in ids])
if m := re.fullmatch(r"/playlists/(\w+)", p):
return self.send_json(playlist(int(m[1][2:])))
if m := re.fullmatch(r"/playlists/(\w+)/(tracks|items)", p):
total = 140
return self.send_json(page([{"track": track(i * 2 + 1)} for i in range(off, min(off + lim, total))], off, lim, total, p))
if m := re.fullmatch(r"/albums/(\w+)", p):
n = int(m[1][2:])
a = album(n)
a["tracks"] = page([track(n * 10 + i, False) for i in range(10)], 0, 50, 10, p)
return self.send_json(a)
if m := re.fullmatch(r"/albums/(\w+)/tracks", p):
return self.send_json(page([], off, lim, 10, p))
if m := re.fullmatch(r"/artists/(\w+)", p):
return self.send_json(artist(int(m[1][2:])))
if m := re.fullmatch(r"/artists/(\w+)/top-tracks", p):
n = int(m[1][2:])
return self.send_json({"tracks": [track(n + 12 * i) for i in range(10)]})
if m := re.fullmatch(r"/artists/(\w+)/albums", p):
n = int(m[1][2:])
return self.send_json(page([album(n + 12 * i) for i in range(6)], 0, 30, 6, p))
if m := re.fullmatch(r"/shows/(\w+)", p):
return self.send_json(show(int(m[1][2:])))
if m := re.fullmatch(r"/shows/(\w+)/episodes", p):
return self.send_json(page([episode(i) for i in range(off, min(off + 50, 30))], off, 50, 30, p))
if p == "/search":
return self.send_json({
"tracks": page([track(i * 11) for i in range(10)], 0, 10, 10, p),
"artists": page([artist(i) for i in range(6)], 0, 10, 6, p),
"albums": page([album(i) for i in range(8)], 0, 10, 8, p),
"playlists": page([None] + [playlist(i) for i in range(6)], 0, 10, 7, p),
"shows": page([show(i) for i in range(3)], 0, 10, 3, p),
})
if p == "/me/player/queue":
return self.send_json({"currently_playing": track(1), "queue": [track(i + 40) for i in range(12)]})
self.send_json({"error": {"status": 404, "message": "not found"}}, 404)
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--port", type=int, default=7890)
a = ap.parse_args()
print(f"mock Spotify Web API on http://127.0.0.1:{a.port}/v1")
ThreadingHTTPServer(("127.0.0.1", a.port), H).serve_forever()
if __name__ == "__main__":
main()