Files
Kronic-Krusaders/kronic/resolver/ytdlp_service.py
T

278 lines
8.2 KiB
Python

\
# Copyright Insidious authors <https://github.com/xrun1/insidious>
# Copyright Kronic resolver modifications
# SPDX-License-Identifier: AGPL-3.0-or-later
from __future__ import annotations
import asyncio
import time
from collections import defaultdict
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass
from typing import Any
import yt_dlp
from yt_dlp import YoutubeDL
from .net import PARALLEL_REQUESTS_PER_HOST, max_parallel_requests
@dataclass(slots=True)
class CacheEntry:
expires: float
value: dict[str, Any]
class YtdlpService:
"""
Minimal yt-dlp wrapper for Kronic.
The old Insidious package model/cache/UI stack is deliberately removed.
Kronic needs only:
- search
- video metadata/formats
- fresh signed media URLs for a selected format
"""
def __init__(self) -> None:
self._pool = ThreadPoolExecutor(
max_workers=PARALLEL_REQUESTS_PER_HOST
)
self._video_cache: dict[str, CacheEntry] = {}
self._search_cache: dict[str, CacheEntry] = {}
self._locks: defaultdict[str, asyncio.Lock] = defaultdict(asyncio.Lock)
# Keep resolved GoogleVideo URLs fresh enough that Kronic never
# depends on the ~6 hour signature lifetime.
self.video_cache_seconds = 20 * 60
self.search_cache_seconds = 5 * 60
self._ydl_opts = {
"quiet": True,
"no_warnings": True,
"skip_download": True,
"ignore_no_formats_error": True,
"noplaylist": True,
}
self._search_opts = {
**self._ydl_opts,
"extract_flat": True,
}
@property
def headers(self) -> dict[str, str]:
# Use yt-dlp's standard browser-like defaults for the HTTP proxy.
with YoutubeDL(self._ydl_opts) as ydl:
return dict(ydl.params.get("http_headers") or {})
@staticmethod
def _normalize_codec(value: Any) -> str | None:
if not value or value == "none":
return None
return str(value)
@classmethod
def _normalize_format(cls, fmt: dict[str, Any]) -> dict[str, Any]:
vcodec = cls._normalize_codec(fmt.get("vcodec"))
acodec = cls._normalize_codec(fmt.get("acodec"))
return {
"id": str(fmt.get("format_id") or ""),
"name": fmt.get("format_note"),
"protocol": fmt.get("protocol"),
"ext": fmt.get("ext"),
"container": fmt.get("container"),
"width": fmt.get("width"),
"height": fmt.get("height"),
"fps": fmt.get("fps"),
"vcodec": vcodec,
"acodec": acodec,
"bitrate": fmt.get("tbr"),
"filesize": fmt.get("filesize") or fmt.get("filesize_approx"),
"audio_channels": fmt.get("audio_channels"),
"language": fmt.get("language"),
"url": fmt.get("url"),
"http_headers": dict(fmt.get("http_headers") or {}),
"video_only": bool(vcodec and not acodec),
"audio_only": bool(acodec and not vcodec),
}
@staticmethod
def _best_thumbnail(data: dict[str, Any]) -> str | None:
thumbs = data.get("thumbnails") or []
if thumbs:
thumbs = sorted(
(t for t in thumbs if t.get("url")),
key=lambda t: (
t.get("width") or 0,
t.get("height") or 0,
),
reverse=True,
)
if thumbs:
return thumbs[0]["url"]
return data.get("thumbnail")
def _extract_video_sync(self, video_id: str) -> dict[str, Any]:
url = f"https://www.youtube.com/watch?v={video_id}"
with YoutubeDL(self._ydl_opts) as ydl:
data = ydl.extract_info(url, download=False)
if not data:
raise RuntimeError(f"yt-dlp returned no data for {video_id}")
formats = [
self._normalize_format(fmt)
for fmt in (data.get("formats") or [])
if fmt.get("format_id") and fmt.get("url")
]
return {
"id": str(data.get("id") or video_id),
"title": data.get("title") or video_id,
"duration": data.get("duration"),
"channel": data.get("channel") or data.get("uploader"),
"channel_id": data.get("channel_id"),
"thumbnail": self._best_thumbnail(data),
"formats": formats,
}
def _search_sync(self, query: str, limit: int) -> dict[str, Any]:
target = f"ytsearch{limit}:{query}"
with YoutubeDL(self._search_opts) as ydl:
data = ydl.extract_info(target, download=False)
items = []
for entry in (data or {}).get("entries") or []:
if not entry:
continue
video_id = entry.get("id")
if not video_id:
continue
items.append({
"id": str(video_id),
"title": entry.get("title") or str(video_id),
"duration": entry.get("duration"),
"channel": entry.get("channel") or entry.get("uploader"),
"channel_id": entry.get("channel_id"),
"thumbnail": self._best_thumbnail(entry),
"webpage_url": (
entry.get("webpage_url")
or f"https://www.youtube.com/watch?v={video_id}"
),
})
return {"items": items}
async def video(
self,
video_id: str,
*,
refresh: bool = False,
) -> dict[str, Any]:
now = time.monotonic()
if not refresh:
cached = self._video_cache.get(video_id)
if cached and cached.expires > now:
return cached.value
async with self._locks[f"video:{video_id}"]:
now = time.monotonic()
if not refresh:
cached = self._video_cache.get(video_id)
if cached and cached.expires > now:
return cached.value
loop = asyncio.get_running_loop()
async with max_parallel_requests("https://youtube.com"):
value = await loop.run_in_executor(
self._pool,
self._extract_video_sync,
video_id,
)
self._video_cache[video_id] = CacheEntry(
expires=time.monotonic() + self.video_cache_seconds,
value=value,
)
return value
async def search(
self,
query: str,
*,
limit: int = 20,
) -> dict[str, Any]:
limit = max(1, min(limit, 50))
key = f"{limit}:{query.strip().lower()}"
now = time.monotonic()
cached = self._search_cache.get(key)
if cached and cached.expires > now:
return cached.value
async with self._locks[f"search:{key}"]:
now = time.monotonic()
cached = self._search_cache.get(key)
if cached and cached.expires > now:
return cached.value
loop = asyncio.get_running_loop()
async with max_parallel_requests("https://youtube.com"):
value = await loop.run_in_executor(
self._pool,
self._search_sync,
query,
limit,
)
self._search_cache[key] = CacheEntry(
expires=time.monotonic() + self.search_cache_seconds,
value=value,
)
return value
async def format(
self,
video_id: str,
format_id: str,
*,
refresh: bool = False,
) -> dict[str, Any]:
video = await self.video(video_id, refresh=refresh)
for fmt in video["formats"]:
if fmt["id"] == format_id:
return fmt
# The format list can change. Re-resolve once before failing.
if not refresh:
return await self.format(
video_id,
format_id,
refresh=True,
)
raise KeyError(
f"format {format_id!r} not found for video {video_id!r}"
)
YTDLP = YtdlpService()