youtube.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. # -*- coding: utf-8 -*-
  2. """
  3. YouTube-Quelle via yt-dlp.
  4. Sucht und laedt YouTube-Audio herunter fuer die Wiedergabe
  5. ueber die bestehende Decoder-Pipeline.
  6. """
  7. import asyncio
  8. import os
  9. import re
  10. import time
  11. from pathlib import Path
  12. from typing import AsyncIterator
  13. from trixy_core.music.sources.base import MusicSource, SourceType, SourceState
  14. from trixy_core.music.track import Track, TrackMetadata, TrackState
  15. from trixy_core.utils.debug import pinfo, pdebug, perror, pwarn
  16. # Optionale Abhaengigkeit
  17. _YT_DLP_AVAILABLE = False
  18. try:
  19. import yt_dlp
  20. _YT_DLP_AVAILABLE = True
  21. except ImportError:
  22. pass
  23. class YouTubeSource(MusicSource):
  24. """YouTube-Quelle via yt-dlp (optional)."""
  25. def __init__(
  26. self,
  27. name: str = "YouTube",
  28. cache_dir: str = "cache/youtube",
  29. max_cache_size_mb: int = 500,
  30. preferred_format: str = "bestaudio[ext=m4a]/bestaudio/best",
  31. max_results: int = 5,
  32. ) -> None:
  33. """
  34. Initialisiert die YouTube-Quelle.
  35. Args:
  36. name: Name der Quelle
  37. cache_dir: Cache-Verzeichnis fuer Downloads
  38. max_cache_size_mb: Maximale Cache-Groesse in MB
  39. preferred_format: yt-dlp Format-String
  40. max_results: Maximale Suchergebnisse
  41. """
  42. super().__init__(name=name, source_type=SourceType.YOUTUBE)
  43. self._cache_dir = Path(cache_dir)
  44. self._max_cache_size_mb = max_cache_size_mb
  45. self._preferred_format = preferred_format
  46. self._max_results = max_results
  47. @property
  48. def is_yt_dlp_available(self) -> bool:
  49. """Prueft ob yt-dlp installiert ist."""
  50. return _YT_DLP_AVAILABLE
  51. async def connect(self) -> bool:
  52. """Prueft ob yt-dlp installiert ist und erstellt Cache-Verzeichnis."""
  53. if not _YT_DLP_AVAILABLE:
  54. pwarn("YouTubeSource: yt-dlp nicht installiert")
  55. self._state = SourceState.UNAVAILABLE
  56. return False
  57. # Cache-Verzeichnis erstellen
  58. try:
  59. self._cache_dir.mkdir(parents=True, exist_ok=True)
  60. self._state = SourceState.AVAILABLE
  61. pinfo("YouTubeSource: Verbunden")
  62. return True
  63. except OSError as e:
  64. perror(f"YouTubeSource: Cache-Verzeichnis konnte nicht erstellt werden: {e}")
  65. self._state = SourceState.ERROR
  66. return False
  67. async def disconnect(self) -> None:
  68. """Trennt die Verbindung."""
  69. self._state = SourceState.UNAVAILABLE
  70. async def scan(self) -> int:
  71. """YouTube unterstuetzt kein Scanning — gibt 0 zurueck."""
  72. return 0
  73. async def get_track(self, track_id: str) -> Track | None:
  74. """Holt Track nach ID."""
  75. return self._tracks.get(track_id)
  76. async def get_audio_stream(self, track: Track) -> AsyncIterator[bytes]:
  77. """Liefert Audio-Daten als Stream (aus heruntergeladener Datei)."""
  78. if not track.path or not track.path.exists():
  79. return
  80. chunk_size = 65536 # 64 KB
  81. def read_file():
  82. with open(track.path, "rb") as f:
  83. while True:
  84. chunk = f.read(chunk_size)
  85. if not chunk:
  86. break
  87. yield chunk
  88. for chunk in await asyncio.to_thread(lambda: list(read_file())):
  89. yield chunk
  90. async def get_metadata(self, track: Track) -> TrackMetadata | None:
  91. """Liefert Metadaten eines Tracks."""
  92. return track.metadata
  93. async def search(self, query: str, limit: int = 5) -> list[Track]:
  94. """
  95. Sucht auf YouTube nach Audio-Tracks.
  96. Args:
  97. query: Suchstring
  98. limit: Maximale Ergebnisse
  99. Returns:
  100. Liste gefundener Tracks
  101. """
  102. if not _YT_DLP_AVAILABLE or self._state != SourceState.AVAILABLE:
  103. return []
  104. effective_limit = min(limit, self._max_results)
  105. ydl_opts = {
  106. "quiet": True,
  107. "no_warnings": True,
  108. "extract_flat": False,
  109. "skip_download": True,
  110. "default_search": f"ytsearch{effective_limit}",
  111. }
  112. try:
  113. results = await asyncio.to_thread(self._search_sync, query, ydl_opts)
  114. return results
  115. except Exception as e:
  116. perror(f"YouTubeSource: Suchfehler: {e}")
  117. return []
  118. def _search_sync(self, query: str, ydl_opts: dict) -> list[Track]:
  119. """Synchrone YouTube-Suche (wird in Thread ausgefuehrt)."""
  120. tracks = []
  121. with yt_dlp.YoutubeDL(ydl_opts) as ydl:
  122. info = ydl.extract_info(query, download=False)
  123. entries = info.get("entries", []) if info else []
  124. if not entries and info:
  125. # Einzelnes Ergebnis (direkte URL)
  126. entries = [info]
  127. for entry in entries:
  128. if not entry:
  129. continue
  130. video_id = entry.get("id", "")
  131. title = entry.get("title", "Unbekannt")
  132. duration = entry.get("duration", 0)
  133. uploader = entry.get("uploader", "")
  134. thumbnail = entry.get("thumbnail", "")
  135. # Artist/Title Parsing: "Artist - Title" Format
  136. artist, track_title = self._parse_title(title, uploader)
  137. metadata = TrackMetadata(
  138. title=track_title,
  139. artist=artist,
  140. duration_ms=int(duration * 1000) if duration else 0,
  141. artwork_url=thumbnail,
  142. )
  143. track = Track(
  144. uri=f"youtube:{video_id}",
  145. source_type="youtube",
  146. source_id=video_id,
  147. metadata=metadata,
  148. state=TrackState.AVAILABLE,
  149. extra={"video_id": video_id, "url": entry.get("webpage_url", "")},
  150. )
  151. tracks.append(track)
  152. return tracks
  153. def _parse_title(self, title: str, uploader: str) -> tuple[str, str]:
  154. """
  155. Parst YouTube-Titel in Artist und Track-Titel.
  156. Args:
  157. title: YouTube-Video-Titel
  158. uploader: Uploader-Name
  159. Returns:
  160. Tuple (artist, track_title)
  161. """
  162. # Muster: "Artist - Title"
  163. if " - " in title:
  164. parts = title.split(" - ", 1)
  165. return parts[0].strip(), parts[1].strip()
  166. # Muster: "Artist | Title"
  167. if " | " in title:
  168. parts = title.split(" | ", 1)
  169. return parts[0].strip(), parts[1].strip()
  170. # Suffixe entfernen (Official Video, Lyric Video, etc.)
  171. cleaned = re.sub(
  172. r'\s*[\(\[\{].*?(official|lyric|music|video|audio|hd|hq|4k).*?[\)\]\}]',
  173. '', title, flags=re.IGNORECASE
  174. ).strip()
  175. return uploader or "Unbekannt", cleaned or title
  176. async def prepare_track(self, track: Track) -> bool:
  177. """
  178. Laedt Audio herunter und setzt track.path.
  179. Args:
  180. track: Track zum Vorbereiten
  181. Returns:
  182. True wenn erfolgreich
  183. """
  184. if not _YT_DLP_AVAILABLE or self._state != SourceState.AVAILABLE:
  185. return False
  186. video_id = track.extra.get("video_id", track.source_id)
  187. if not video_id:
  188. perror("YouTubeSource: Keine video_id fuer Download")
  189. return False
  190. # Cache pruefen
  191. cached_path = self._get_cached_path(video_id)
  192. if cached_path:
  193. track.path = cached_path
  194. track.state = TrackState.AVAILABLE
  195. pdebug(f"YouTubeSource: Cache-Treffer: {cached_path.name}")
  196. return True
  197. # Herunterladen
  198. track.state = TrackState.LOADING
  199. try:
  200. output_path = await asyncio.to_thread(
  201. self._download_sync, video_id
  202. )
  203. if output_path and output_path.exists():
  204. track.path = output_path
  205. track.state = TrackState.AVAILABLE
  206. pinfo(f"YouTubeSource: Heruntergeladen: {output_path.name}")
  207. # Cache aufraeumen
  208. await self.cleanup_cache()
  209. return True
  210. else:
  211. track.state = TrackState.ERROR
  212. track.error_message = "Download fehlgeschlagen"
  213. return False
  214. except Exception as e:
  215. perror(f"YouTubeSource: Download-Fehler: {e}")
  216. track.state = TrackState.ERROR
  217. track.error_message = str(e)
  218. return False
  219. def _download_sync(self, video_id: str) -> Path | None:
  220. """Synchroner Download (wird in Thread ausgefuehrt)."""
  221. output_template = str(self._cache_dir / f"{video_id}.%(ext)s")
  222. ydl_opts = {
  223. "format": self._preferred_format,
  224. "outtmpl": output_template,
  225. "quiet": True,
  226. "no_warnings": True,
  227. "postprocessors": [{
  228. "key": "FFmpegExtractAudio",
  229. "preferredcodec": "mp3",
  230. "preferredquality": "192",
  231. }],
  232. }
  233. url = f"https://www.youtube.com/watch?v={video_id}"
  234. with yt_dlp.YoutubeDL(ydl_opts) as ydl:
  235. ydl.download([url])
  236. # Ergebnis-Datei finden (yt-dlp aendert Extension nach Postprocessing)
  237. expected_path = self._cache_dir / f"{video_id}.mp3"
  238. if expected_path.exists():
  239. return expected_path
  240. # Fallback: Suche nach video_id im Dateinamen
  241. for f in self._cache_dir.iterdir():
  242. if f.stem == video_id and f.is_file():
  243. return f
  244. return None
  245. def _get_cached_path(self, video_id: str) -> Path | None:
  246. """Prueft ob eine Datei im Cache liegt."""
  247. if not self._cache_dir.exists():
  248. return None
  249. for f in self._cache_dir.iterdir():
  250. if f.stem == video_id and f.is_file():
  251. return f
  252. return None
  253. async def cleanup_cache(self) -> int:
  254. """
  255. Entfernt aelteste Dateien wenn Cache zu gross.
  256. Returns:
  257. Anzahl entfernter Dateien
  258. """
  259. if not self._cache_dir.exists():
  260. return 0
  261. return await asyncio.to_thread(self._cleanup_cache_sync)
  262. def _cleanup_cache_sync(self) -> int:
  263. """Synchrone Cache-Bereinigung."""
  264. # Alle Dateien mit Groesse und Zeitstempel
  265. files: list[tuple[Path, float, int]] = []
  266. total_size = 0
  267. for f in self._cache_dir.iterdir():
  268. if f.is_file():
  269. stat = f.stat()
  270. files.append((f, stat.st_mtime, stat.st_size))
  271. total_size += stat.st_size
  272. max_size = self._max_cache_size_mb * 1024 * 1024
  273. if total_size <= max_size:
  274. return 0
  275. # Nach Aenderungsdatum sortieren (aelteste zuerst)
  276. files.sort(key=lambda x: x[1])
  277. removed = 0
  278. for file_path, _, size in files:
  279. if total_size <= max_size:
  280. break
  281. try:
  282. file_path.unlink()
  283. total_size -= size
  284. removed += 1
  285. except OSError:
  286. pass
  287. if removed > 0:
  288. pdebug(f"YouTubeSource: {removed} Cache-Dateien entfernt")
  289. return removed