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)