forked from trav/lintunes
v0.4.0: cast to a Chromecast from the Connections menu
The Device menu becomes Connections, with "Connect to Chromecast…" beside the Rabbit sync. It opens a dialog that spins while it searches and lists devices as they appear; picking one hands playback over, puts a small cast glyph under the volume slider, and clicking that glyph disconnects. Media-receiver model: lintunes serves the original file over the LAN on an ephemeral port and the Chromecast decodes it itself. Bit-exact — no transcode, no second lossy encode — and the device buffers for itself. The cost is that lintunes is a remote control while connected: no local PCM, so the visualizer shows the cast glyph instead of bars, and transport actions land with about a second of round trip. Player now walks its queue through a swappable PlaybackSink. It keeps owning the queue, shuffle walk, start/stop times and the play-count and scrobble bookkeeping, so casting counts plays and scrobbles exactly like local playback. set_sink() carries track, position and playing-state both ways, so connecting and disconnecting pick up mid-song. LocalSink stays in player.py because the Player tests stub Qt Multimedia in that namespace. The URL carries an opaque random token, never a path, so there is nothing to traverse with; only the last few played tracks stay resolvable and the whole map dies with the session. Range and HEAD are implemented because the device seeks by re-requesting ranges and won't report a duration without them. Failure handling, verified against a real device: a dropped socket gets a 15s grace period, since pychromecast retries on its own and a Wi-Fi blip heals itself. A real loss, another app taking the device, or a network change falls back to local playback still playing, at the same position — the sink reports the state lintunes last asked for rather than the IDLE status a dying connection pushes just before it goes. Quitting stops the device instead of leaving it fetching from a server that just died. The ~119 Apple Lossless / AIFF / protected-AAC tracks are skipped with a status-bar message; the other 21,000+ MP3 and AAC files cast natively. New dependency: pychromecast>=14.0.10, imported lazily so the app still launches where it isn't installed (the menu item then explains the install), and python_requires raised to >=3.11 to match its floor. NOTE: the other machine needs `pip install -e .` before casting appears. tests/test_round29.py: 67 tests; 440 pass overall.
This commit is contained in:
@@ -0,0 +1,182 @@
|
||||
"""A minimal local HTTP server that hands single files to the Chromecast.
|
||||
|
||||
The device fetches audio over the LAN, so it needs a URL rather than a path.
|
||||
This is the only server code in lintunes, so the exposure is kept as small as
|
||||
it can be:
|
||||
|
||||
* It binds an ephemeral port and lives only as long as the cast session.
|
||||
* The URL never carries a path. ``publish()`` mints an opaque random token and
|
||||
keeps the ``token -> absolute path`` mapping in memory; an unknown token is a
|
||||
404. Path traversal isn't defended against, it's structurally impossible —
|
||||
there is no path in the request to traverse with.
|
||||
* Only tracks actually being cast are published, and only the few most recent
|
||||
stay resolvable.
|
||||
|
||||
Range requests are mandatory, not an optimization: the Chromecast seeks by
|
||||
re-requesting byte ranges, and won't report a duration without ``Accept-Ranges``.
|
||||
"""
|
||||
|
||||
import secrets
|
||||
import threading
|
||||
from http import HTTPStatus
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
|
||||
from lintunes.cast.support import parse_range
|
||||
|
||||
# How many previously published tracks stay resolvable. More than one because
|
||||
# the device re-requests the current file when it seeks and can briefly reach
|
||||
# back for the previous one across a track change; small because every live
|
||||
# token is a file this machine will hand to anything on the LAN that asks.
|
||||
KEEP_TOKENS = 3
|
||||
|
||||
CHUNK = 64 * 1024
|
||||
|
||||
|
||||
class _Handler(BaseHTTPRequestHandler):
|
||||
protocol_version = "HTTP/1.1" # Chromecast wants keep-alive + Content-Length
|
||||
|
||||
# BaseHTTPRequestHandler logs every request to stderr; the app has a status
|
||||
# bar for anything worth saying.
|
||||
def log_message(self, format, *args):
|
||||
pass
|
||||
|
||||
@property
|
||||
def _tracks(self):
|
||||
return self.server.track_server
|
||||
|
||||
def _resolve(self) -> Path | None:
|
||||
prefix = "/t/"
|
||||
if not self.path.startswith(prefix):
|
||||
return None
|
||||
return self._tracks.lookup(self.path[len(prefix):])
|
||||
|
||||
def do_HEAD(self):
|
||||
self._serve(body=False)
|
||||
|
||||
def do_GET(self):
|
||||
self._serve(body=True)
|
||||
|
||||
def _serve(self, body: bool):
|
||||
path = self._resolve()
|
||||
if path is None:
|
||||
self.send_error(HTTPStatus.NOT_FOUND)
|
||||
return
|
||||
try:
|
||||
size = path.stat().st_size
|
||||
handle = open(path, "rb")
|
||||
except OSError:
|
||||
# The file moved or the drive went away since it was published.
|
||||
self.send_error(HTTPStatus.NOT_FOUND)
|
||||
return
|
||||
|
||||
with handle:
|
||||
span = parse_range(self.headers.get("Range"), size)
|
||||
if span is None:
|
||||
start, end = 0, max(size - 1, 0)
|
||||
status = HTTPStatus.OK
|
||||
else:
|
||||
start, end = span
|
||||
status = HTTPStatus.PARTIAL_CONTENT
|
||||
length = end - start + 1 if size else 0
|
||||
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", self._tracks.content_type(path))
|
||||
self.send_header("Accept-Ranges", "bytes")
|
||||
self.send_header("Content-Length", str(length))
|
||||
if status == HTTPStatus.PARTIAL_CONTENT:
|
||||
self.send_header("Content-Range", f"bytes {start}-{end}/{size}")
|
||||
self.end_headers()
|
||||
if not body or not length:
|
||||
return
|
||||
|
||||
handle.seek(start)
|
||||
remaining = length
|
||||
try:
|
||||
while remaining > 0:
|
||||
chunk = handle.read(min(CHUNK, remaining))
|
||||
if not chunk:
|
||||
break
|
||||
self.wfile.write(chunk)
|
||||
remaining -= len(chunk)
|
||||
except (BrokenPipeError, ConnectionResetError):
|
||||
# Normal: the device drops the connection the moment it seeks
|
||||
# or the track is replaced. Nothing to report.
|
||||
pass
|
||||
|
||||
|
||||
class TrackServer:
|
||||
"""Serves published files over the LAN for the duration of a cast session.
|
||||
|
||||
Thread-safe: ``publish`` is called from the GUI thread while the server's
|
||||
own threads read the token map.
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
self._httpd: ThreadingHTTPServer | None = None
|
||||
self._thread: threading.Thread | None = None
|
||||
self._lock = threading.Lock()
|
||||
self._tokens: dict[str, Path] = {}
|
||||
self._types: dict[Path, str] = {}
|
||||
self._order: list[str] = []
|
||||
|
||||
# ---- lifecycle ----
|
||||
|
||||
def start(self) -> int:
|
||||
"""Bind an ephemeral port on every interface and serve. Returns the port."""
|
||||
if self._httpd is not None:
|
||||
return self.port
|
||||
# 0.0.0.0, not localhost: the Chromecast fetches from another machine.
|
||||
httpd = ThreadingHTTPServer(("0.0.0.0", 0), _Handler)
|
||||
httpd.daemon_threads = True
|
||||
httpd.track_server = self
|
||||
self._httpd = httpd
|
||||
self._thread = threading.Thread(target=httpd.serve_forever, daemon=True)
|
||||
self._thread.start()
|
||||
return self.port
|
||||
|
||||
@property
|
||||
def port(self) -> int:
|
||||
return self._httpd.server_address[1] if self._httpd else 0
|
||||
|
||||
def stop(self):
|
||||
"""Shut the listener down. Idempotent."""
|
||||
httpd, self._httpd = self._httpd, None
|
||||
if httpd is not None:
|
||||
httpd.shutdown()
|
||||
httpd.server_close()
|
||||
self._thread = None
|
||||
with self._lock:
|
||||
self._tokens.clear()
|
||||
self._types.clear()
|
||||
self._order.clear()
|
||||
|
||||
# ---- publishing ----
|
||||
|
||||
def publish(self, path, content_type: str) -> str:
|
||||
"""Make `path` fetchable and return its token."""
|
||||
path = Path(path)
|
||||
with self._lock:
|
||||
token = secrets.token_urlsafe(16)
|
||||
self._tokens[token] = path
|
||||
self._types[path] = content_type
|
||||
self._order.append(token)
|
||||
# Drop the oldest so a long listening session doesn't leave the
|
||||
# whole played history reachable.
|
||||
while len(self._order) > KEEP_TOKENS:
|
||||
stale = self._order.pop(0)
|
||||
dropped = self._tokens.pop(stale, None)
|
||||
if dropped is not None and dropped not in self._tokens.values():
|
||||
self._types.pop(dropped, None)
|
||||
return token
|
||||
|
||||
def lookup(self, token: str) -> Path | None:
|
||||
with self._lock:
|
||||
return self._tokens.get(token)
|
||||
|
||||
def content_type(self, path: Path) -> str:
|
||||
with self._lock:
|
||||
return self._types.get(path, "application/octet-stream")
|
||||
|
||||
def url_for(self, host: str, token: str) -> str:
|
||||
return f"http://{host}:{self.port}/t/{token}"
|
||||
Reference in New Issue
Block a user