diff --git a/kronic/cast/__init__.py b/kronic/cast/__init__.py new file mode 100644 index 0000000..cfaf96b --- /dev/null +++ b/kronic/cast/__init__.py @@ -0,0 +1,2 @@ +from .service import get_cast_service, start_cast_service, stop_cast_service +from .bridge import bridge diff --git a/kronic/cast/bridge.py b/kronic/cast/bridge.py new file mode 100644 index 0000000..fc8cf9d --- /dev/null +++ b/kronic/cast/bridge.py @@ -0,0 +1,165 @@ +from __future__ import annotations + +import threading +import time + + +STATUS_PLAYING = 1 +STATUS_PAUSED = 2 +STATUS_LOADING = 3 +STATUS_STOPPED = 4 + +_STATUS_NAMES = { + STATUS_PLAYING: "playing", + STATUS_PAUSED: "paused", + STATUS_LOADING: "loading", + STATUS_STOPPED: "stopped", +} + + +class CastBridge: + """Thread-safe bridge between the YouTube receiver and one Kronic browser.""" + + def __init__(self): + self._condition = threading.Condition() + self._sequence = 0 + self._command = None + + self._active_client = None + self._active_client_seen = 0.0 + self._client_timeout = 30.0 + + self._state = { + "status": STATUS_STOPPED, + "position": 0.0, + "duration": 0.0, + "volume": 100, + "muted": False, + "video_id": None, + } + self._state_reporter = None + + def set_state_reporter(self, callback): + with self._condition: + self._state_reporter = callback + + def publish(self, command, **data): + with self._condition: + self._sequence += 1 + self._command = { + "seq": self._sequence, + "command": str(command), + **data, + } + if "video_id" in data: + self._state["video_id"] = data.get("video_id") + self._condition.notify_all() + return dict(self._command) + + def _claim_or_refresh(self, client_id): + now = time.monotonic() + stale = ( + not self._active_client + or (now - self._active_client_seen) > self._client_timeout + ) + if stale: + self._active_client = client_id + if client_id == self._active_client: + self._active_client_seen = now + return True + return False + + def wait_for_command(self, client_id, after=0, timeout=20.0): + client_id = str(client_id or "").strip() + if not client_id: + return { + "active": False, + "seq": self._sequence, + "reason": "client_id required", + } + + deadline = time.monotonic() + max(0.0, min(float(timeout), 25.0)) + + with self._condition: + if not self._claim_or_refresh(client_id): + return { + "active": False, + "seq": self._sequence, + "standby": True, + } + + while self._sequence <= int(after or 0): + remaining = deadline - time.monotonic() + if remaining <= 0: + return { + "active": True, + "seq": self._sequence, + "command": None, + } + self._condition.wait(min(remaining, 5.0)) + if not self._claim_or_refresh(client_id): + return { + "active": False, + "seq": self._sequence, + "standby": True, + } + + return { + "active": True, + **dict(self._command or {"seq": self._sequence, "command": None}), + } + + def player_state(self): + with self._condition: + return dict(self._state) + + def update_player_state( + self, + *, + client_id, + status, + position=0, + duration=0, + volume=None, + muted=None, + video_id=None, + ): + with self._condition: + if client_id and not self._claim_or_refresh(str(client_id)): + return {"accepted": False, "standby": True, **self._state} + + status_code = status + if isinstance(status, str): + lookup = { + "playing": STATUS_PLAYING, + "paused": STATUS_PAUSED, + "loading": STATUS_LOADING, + "stopped": STATUS_STOPPED, + "ended": STATUS_STOPPED, + } + status_code = lookup.get(status.lower(), STATUS_STOPPED) + + self._state["status"] = int(status_code) + self._state["position"] = max(0.0, float(position or 0)) + self._state["duration"] = max(0.0, float(duration or 0)) + if volume is not None: + self._state["volume"] = max(0, min(100, int(volume))) + if muted is not None: + self._state["muted"] = bool(muted) + if video_id is not None: + self._state["video_id"] = str(video_id or "") or None + + snapshot = dict(self._state) + reporter = self._state_reporter + + if reporter is not None: + reporter(snapshot) + + return { + "accepted": True, + **snapshot, + "status_name": _STATUS_NAMES.get(snapshot["status"], "stopped"), + } + + +bridge = CastBridge() diff --git a/kronic/cast/command_parser.py b/kronic/cast/command_parser.py new file mode 100644 index 0000000..9da5e0d --- /dev/null +++ b/kronic/cast/command_parser.py @@ -0,0 +1,56 @@ +from __future__ import annotations + +import ast +import logging +import re +from collections import namedtuple + +logger = logging.getLogger("kronic.cast.commands") + +Command = namedtuple("Command", ("code", "name", "data")) + +CMD_PATTERN = re.compile( + r'\[(?P\d+),\["(?P.+?)"(?:,(?P.*?))?\]\]' +) + + +def _command_from_match(match): + code = int(match.group("code")) + name = match.group("cmd") + raw_data = match.group("data") + data = ast.literal_eval(raw_data) if raw_data else None + return Command(code, name, data) + + +class CommandParser: + """Buffering parser for the YouTube lounge/bind command stream.""" + + def __init__(self, buf=None): + self.pending = "" + if buf: + self.write(buf) + + def __iter__(self): + return self._parse_pending() + + def _parse_pending(self): + if not self.pending: + return + + end_index = 0 + try: + for match in CMD_PATTERN.finditer(self.pending): + end_index = match.end() + try: + yield _command_from_match(match) + except (SyntaxError, ValueError): + logger.exception("Unable to parse YouTube cast command") + finally: + self.pending = self.pending[end_index:] + + def write(self, value): + for line in str(value).splitlines(): + self.pending += line + + def get_commands(self): + return tuple(self)