"""Async wrappers around the ``yt-dlp`` command line tool. Two operations are needed by the application: * :func:`fetch_info` runs ``yt-dlp -i --dump-json `` and parses the resulting JSON document. * :func:`download` runs ``yt-dlp -i -o -f `` and reports download progress back to the caller. Both are ``async`` because they drive an external process and must not block the Textual event loop. """ from __future__ import annotations import asyncio import json import re from collections.abc import Awaitable, Callable from typing import Any #: Matches yt-dlp's ``--newline`` progress output, e.g. #: "[download] 12.3% of 50.00MiB at 1.20MiB/s ETA 00:30" _PROGRESS_RE = re.compile(r"\[download\]\s+(\d{1,3}(?:\.\d+)?)%") ProgressCallback = Callable[[float], Awaitable[None]] class YtDlpError(RuntimeError): """Raised when yt-dlp fails or returns unusable output.""" async def fetch_info(url: str) -> dict[str, Any]: """Run ``yt-dlp -i --dump-json `` and return the parsed JSON. Raises :class:`YtDlpError` if the process fails or produces no usable JSON document. """ process = await asyncio.create_subprocess_exec( "yt-dlp", "-i", "--dump-json", url, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, ) stdout, stderr = await process.communicate() document = _first_json_object(stdout.decode("utf-8", errors="replace")) if document is not None: return document message = stderr.decode("utf-8", errors="replace").strip() raise YtDlpError(message or "yt-dlp produced no information for this URL.") def _first_json_object(text: str) -> dict[str, Any] | None: """Return the first line of ``text`` that parses as a JSON object.""" for line in text.splitlines(): line = line.strip() if not line.startswith("{"): continue try: data = json.loads(line) except json.JSONDecodeError: continue if isinstance(data, dict): return data return None async def download( url: str, destination: str, format_id: str, on_progress: ProgressCallback | None = None, ) -> None: """Run ``yt-dlp -i url -o destination -f format_id``. ``on_progress`` is awaited with the current percentage (0-100) whenever the reported progress changes by at least one percentage point. Raises :class:`YtDlpError` if the process exits with a non-zero status. """ process = await asyncio.create_subprocess_exec( "yt-dlp", "--newline", "-i", url, "-o", destination, "-f", format_id, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT, ) last_reported = -1 assert process.stdout is not None stderr_lines: list[str] = [] while True: raw_line = await process.stdout.readline() if not raw_line: break line = raw_line.decode("utf-8", errors="replace").rstrip() stderr_lines.append(line) match = _PROGRESS_RE.search(line) if match and on_progress is not None: percent = float(match.group(1)) if int(percent) != last_reported: last_reported = int(percent) await on_progress(percent) return_code = await process.wait() if return_code != 0: tail = "\n".join(stderr_lines[-10:]) raise YtDlpError(tail or f"yt-dlp exited with status {return_code}.")