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52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
"""YouTube links: URL checks, a quick metadata probe, the audio download (yt-dlp) and the saved sign-in cookies.



Some networks get YouTube's "Sign in to confirm you're not a bot" check for every video; only cookies from a

signed-in browser session get past it. The user uploads a cookies.txt export once. StemDeck keeps only the

youtube.com lines, stores them in <data_dir>/youtube-cookies.txt and hands yt-dlp a private copy for each run

(yt-dlp rewrites its cookie file non-atomically, so the stored file is never given to it directly).



`python -m stemdeck.youtube probe <url>` prints one JSON line; the API runs it as a subprocess so a hung

extraction can be killed with a timeout.

"""

from __future__ import annotations

import contextlib
import json
import logging
import os
import re
import shutil
import subprocess
import sys
import tempfile
import time
from collections.abc import Callable, Iterator
from contextlib import contextmanager
from dataclasses import asdict, dataclass
from pathlib import Path
from typing import Any
from urllib.parse import parse_qs, urlsplit

from stemdeck.settings import Settings, details_hint, get_settings

log = logging.getLogger(__name__)

PROBE_TIMEOUT_SEC = 90.0
SOCKET_TIMEOUT_SEC = 30.0
MAX_COOKIE_UPLOAD_BYTES = 1024 * 1024
COOKIE_FILE_HEADER = "# Netscape HTTP Cookie File\n"
COOKIES_FILENAME = "youtube-cookies.txt"
COPIES_DIRNAME = "youtube-cookie-copies"
STALE_COPY_SEC = 3600.0  # far longer than any probe or download; younger copies may still be in use
_ERROR_DETAIL_CHARS = 200

YOUTUBE_HOSTS = frozenset({"youtube.com", "m.youtube.com", "music.youtube.com", "youtu.be",
                           "youtube-nocookie.com"})
VIDEO_ID = re.compile(r"[A-Za-z0-9_-]{11}")
# Path prefixes that carry the video id as the next path segment.
_ID_PATH_PREFIXES = ("shorts", "live", "embed", "v", "e")
# Cookies that only exist in a signed-in session; without one YouTube's bot check still fails.
SIGNED_IN_COOKIES = frozenset({"SAPISID", "__Secure-1PAPISID", "__Secure-3PAPISID", "__Secure-1PSID",
                               "__Secure-3PSID", "SID", "LOGIN_INFO"})
_HTTPONLY_PREFIX = "#HttpOnly_"
_COOKIE_FIELDS = 7
_PARTIAL_SUFFIXES = (".part", ".ytdl")


class YouTubeError(RuntimeError):
    """A YouTube link could not be used; the message is written for the user."""


@dataclass(frozen=True)
class VideoInfo:
    video_id: str
    url: str
    title: str
    artist: str | None
    duration_sec: float | None
    is_live: bool


# ------------------------------------------------------------------ links
def canonical_url(raw: str) -> str:
    """Return `https://www.youtube.com/watch?v=<id>` for any YouTube video link, else raise YouTubeError.



    Only YouTube hosts are accepted, so yt-dlp is never pointed at an arbitrary (e.g. local) address."""
    text = raw.strip()
    if not text:
        raise YouTubeError("Paste a YouTube link first.")
    if "://" not in text:
        text = f"https://{text}"
    try:
        parts = urlsplit(text)
        host = (parts.hostname or "").lower().removeprefix("www.")
    except ValueError as exc:
        raise YouTubeError("That doesn't look like a YouTube link.") from exc
    if parts.scheme not in ("http", "https") or host not in YOUTUBE_HOSTS:
        raise YouTubeError("Only YouTube links are supported (youtube.com or youtu.be).")
    query = parse_qs(parts.query)
    video_id = _video_id(host, parts.path, query)
    if video_id is None:
        if "list" in query:
            raise YouTubeError("Playlists aren't supported. Paste the link of a single video.")
        raise YouTubeError("That YouTube link doesn't point to a video.")
    return f"https://www.youtube.com/watch?v={video_id}"


def _video_id(host: str, path: str, query: dict[str, list[str]]) -> str | None:
    segments = [s for s in path.split("/") if s]
    if host == "youtu.be":
        candidate = segments[0] if segments else None
    elif segments[:1] == ["watch"]:
        candidate = (query.get("v") or [None])[0]
    elif len(segments) >= 2 and segments[0] in _ID_PATH_PREFIXES:
        candidate = segments[1]
    else:
        candidate = None
    return candidate if candidate and VIDEO_ID.fullmatch(candidate) else None


# ------------------------------------------------------------------ cookies
def cookies_path(settings: Settings) -> Path:
    return settings.data_dir / COOKIES_FILENAME


def has_cookies(settings: Settings) -> bool:
    return cookies_path(settings).is_file()


def save_cookies(settings: Settings, data: bytes) -> int:
    """Validate a cookies.txt export, keep only its youtube.com cookies and store them. Returns how many."""
    if len(data) > MAX_COOKIE_UPLOAD_BYTES:
        raise YouTubeError("That file is too big for a cookies.txt export (limit 1 MB).")
    try:
        text = data.decode("utf-8-sig")
    except UnicodeDecodeError as exc:
        raise YouTubeError("That file isn't a cookies.txt export (it isn't plain text).") from exc
    kept: list[str] = []
    names: set[str] = set()
    for line in text.splitlines():
        fields = line.split("\t")
        if len(fields) != _COOKIE_FIELDS:
            continue
        domain = fields[0].removeprefix(_HTTPONLY_PREFIX).lstrip(".").lower()
        if domain == "youtube.com" or domain.endswith(".youtube.com"):
            kept.append(line)
            names.add(fields[5])
    if not kept:
        raise YouTubeError("No youtube.com cookies found. Export the cookies while a YouTube tab is open, "
                           "in the Netscape (cookies.txt) format.")
    if not names & SIGNED_IN_COOKIES:
        raise YouTubeError("These cookies are from a signed-out session. Sign in to YouTube in that browser "
                           "window first, then export again.")
    target = cookies_path(settings)
    tmp = target.with_suffix(".tmp")
    tmp.write_text(COOKIE_FILE_HEADER + "\n".join(kept) + "\n", encoding="utf-8")
    os.replace(tmp, target)
    log.info("saved %d YouTube cookies", len(kept))
    return len(kept)


def delete_cookies(settings: Settings) -> None:
    """Remove the saved sign-in, including any per-run copies a killed job or probe left behind."""
    cookies_path(settings).unlink(missing_ok=True)
    sweep_cookie_copies(settings, older_than_sec=0.0)


def _copies_dir(settings: Settings) -> Path:
    return settings.data_dir / COPIES_DIRNAME


def sweep_cookie_copies(settings: Settings, older_than_sec: float = STALE_COPY_SEC) -> None:
    """Delete per-run cookie copies older than `older_than_sec`. A cancel or a probe timeout kills the process

    before it can delete its copy; the age limit keeps the copy of a run that is still going (workers outlive

    server restarts)."""
    cutoff = time.time() - older_than_sec
    for copy in _copies_dir(settings).glob("yt-cookies-*.txt"):
        with contextlib.suppress(OSError):
            if copy.stat().st_mtime <= cutoff:
                copy.unlink()


@contextmanager
def _cookie_copy(settings: Settings) -> Iterator[Path | None]:
    """A throwaway copy of the saved cookies for one yt-dlp run (deleted afterwards), or None."""
    source = cookies_path(settings)
    if not source.is_file():
        yield None
        return
    sweep_cookie_copies(settings)
    copies = _copies_dir(settings)
    copies.mkdir(parents=True, exist_ok=True)
    fd, name = tempfile.mkstemp(prefix="yt-cookies-", suffix=".txt", dir=copies)
    os.close(fd)
    copy = Path(name)
    try:
        shutil.copyfile(source, copy)
        yield copy
    finally:
        copy.unlink(missing_ok=True)


# ------------------------------------------------------------------ yt-dlp
def js_runtime() -> str | None:
    """The JavaScript runtime yt-dlp will use for YouTube's player challenges (Deno preferred)."""
    for name in ("deno", "node"):
        if shutil.which(name):
            return name
    return None


class _YtDlpLogger:
    """Routes yt-dlp output to our log (never to stdout, which the probe uses for its JSON result)."""

    def debug(self, msg: str) -> None:
        if not msg.startswith("[debug] "):
            log.debug("yt-dlp: %s", msg)

    def info(self, msg: str) -> None:
        log.debug("yt-dlp: %s", msg)

    def warning(self, msg: str) -> None:
        log.info("yt-dlp warning: %s", msg)

    def error(self, msg: str) -> None:
        log.warning("yt-dlp error: %s", msg)


@contextmanager
def _youtube_dl(settings: Settings, **extra: Any) -> Iterator[Any]:
    import yt_dlp

    options: dict[str, Any] = {
        "logger": _YtDlpLogger(),
        "quiet": True,
        "noprogress": True,
        "noplaylist": True,
        "allowed_extractors": ["youtube"],
        "socket_timeout": SOCKET_TIMEOUT_SEC,
        "cachedir": str(settings.models_dir / "yt-dlp"),
        "js_runtimes": {"deno": {}, "node": {}},
        **extra,
    }
    with _cookie_copy(settings) as cookie_file:
        if cookie_file is not None:
            options["cookiefile"] = str(cookie_file)
        try:
            with yt_dlp.YoutubeDL(options) as ydl:
                yield ydl
        except yt_dlp.utils.YoutubeDLError as exc:  # DownloadError, or ExtractorError from process_ie_result
            raise YouTubeError(friendly_error(str(exc), signed_in=cookie_file is not None,
                                              public=settings.public)) from exc


def _info_from(raw: dict[str, Any], url: str) -> VideoInfo:
    uploader = str(raw.get("uploader") or "")
    artist = raw.get("artist") or raw.get("creator") or (uploader.removesuffix(" - Topic")
                                                          if uploader.endswith(" - Topic") else None)
    duration = raw.get("duration")
    return VideoInfo(
        video_id=str(raw.get("id") or url.rsplit("=", 1)[-1]),
        url=url,
        title=str(raw.get("track") or raw.get("title") or "YouTube video")[:200],
        artist=str(artist)[:200] if artist else None,
        duration_sec=float(duration) if isinstance(duration, int | float) else None,
        is_live=bool(raw.get("is_live")) or raw.get("live_status") in ("is_live", "is_upcoming"),
    )


def check_video(info: VideoInfo, max_duration_sec: float) -> None:
    if info.is_live:
        raise YouTubeError("Live streams and upcoming premieres can't be split. Try again once it has ended.")
    if info.duration_sec is not None and info.duration_sec > max_duration_sec:
        raise YouTubeError(f"This video is {info.duration_sec / 60:.1f} min long; the limit is "
                           f"{max_duration_sec / 60:.0f} min (max_duration_sec in config.yaml).")


def fetch_info(url: str, settings: Settings) -> VideoInfo:
    """Title, artist and length of a video, without downloading it (runs yt-dlp in this process)."""
    with _youtube_dl(settings) as ydl:
        raw = ydl.extract_info(url, download=False)
    return _info_from(raw or {}, url)


def probe(url: str, settings: Settings | None = None) -> VideoInfo:
    """fetch_info() in a subprocess with a hard timeout, for the API server."""
    settings = settings or get_settings()
    cmd = [sys.executable, "-m", "stemdeck.youtube", "probe", url]
    try:
        result = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", errors="replace",
                                timeout=PROBE_TIMEOUT_SEC, stdin=subprocess.DEVNULL, check=False,
                                env={**os.environ, "PYTHONIOENCODING": "utf-8",
                                     "STEMDECK_DATA_DIR": str(settings.data_dir)})
    except subprocess.TimeoutExpired as exc:
        raise YouTubeError("YouTube took too long to answer. Check your internet connection and try again.") from exc
    except OSError as exc:
        raise YouTubeError(f"Could not run the YouTube helper: {exc}") from exc
    lines = [line for line in result.stdout.splitlines() if line.startswith("{")]
    unreadable = f"Could not read this YouTube link. {details_hint('server.log')}"
    if not lines:
        log.warning("YouTube probe exited with %s: %s", result.returncode, result.stderr[-500:])
        raise YouTubeError(unreadable)
    try:
        payload = json.loads(lines[-1])
        if "error" in payload:
            raise YouTubeError(str(payload["error"]))
        return VideoInfo(**payload)
    except (json.JSONDecodeError, TypeError) as exc:
        log.warning("YouTube probe printed an unexpected result: %r", lines[-1][:500])
        raise YouTubeError(unreadable) from exc


def download_audio(url: str, dest_dir: Path, settings: Settings, max_duration_sec: float,

                   max_bytes: int, on_progress: Callable[[float, str], None]) -> Path:
    """Download the best audio-only stream of `url` into `dest_dir` and return the file path."""
    return download_song(url, dest_dir, settings, max_duration_sec, max_bytes, on_progress)[0]


def download_song(url: str, dest_dir: Path, settings: Settings, max_duration_sec: float,

                  max_bytes: int, on_progress: Callable[[float, str], None]) -> tuple[Path, VideoInfo]:
    """Download the best audio-only stream of `url` into `dest_dir`; returns the file and the video's details.

    Partial files from an interrupted try are kept (yt-dlp resumes them); finished leftovers are removed so they

    can't be mistaken for this run's download."""
    dest_dir.mkdir(parents=True, exist_ok=True)
    for leftover in dest_dir.glob("audio.*"):
        if leftover.suffix not in _PARTIAL_SUFFIXES:
            leftover.unlink(missing_ok=True)

    def hook(status: dict[str, Any]) -> None:
        if status.get("status") != "downloading":
            return
        done = float(status.get("downloaded_bytes") or 0)
        total = float(status.get("total_bytes") or status.get("total_bytes_estimate") or 0)
        if total > 0:
            on_progress(done / total, f"{done / 1e6:.1f} of {total / 1e6:.1f} MB")

    with _youtube_dl(settings, format="bestaudio/best", outtmpl={"default": "audio.%(ext)s"},
                     paths={"home": str(dest_dir), "temp": str(dest_dir)}, progress_hooks=[hook],
                     max_filesize=max_bytes, overwrites=True) as ydl:
        raw = ydl.extract_info(url, download=False) or {}
        info = _info_from(raw, url)
        check_video(info, max_duration_sec)
        result = ydl.process_ie_result(raw, download=True) or {}
    downloads = result.get("requested_downloads") or []
    path = Path(downloads[0]["filepath"]) if downloads and downloads[0].get("filepath") else None
    if path is None or not path.is_file():
        path = next((p for p in dest_dir.glob("audio.*") if p.suffix not in _PARTIAL_SUFFIXES), None)
    if path is None or path.stat().st_size == 0:
        raise YouTubeError("YouTube didn't send any audio for this video (it may be too big or "
                           "region-locked). Try another link.")
    return path, info


# ------------------------------------------------------------------ error messages
_SIGN_IN_HELP = "Set up the YouTube sign-in (under the link box on the home page), then try again."
# On the public site visitors can't fix the server's setup, so their messages point at the upload instead.
_UPLOAD_INSTEAD = "Download the song yourself and upload the file instead, or try again later."
PUBLIC_BLOCKED = "YouTube is blocking downloads from this server right now. " + _UPLOAD_INSTEAD


@dataclass(frozen=True)
class _Rule:
    needles: tuple[str, ...]
    text: str
    public_text: str | None = None  # for visitors of the public site, when it differs


_ERROR_RULES: tuple[_Rule, ...] = (
    _Rule(("confirm your age", "age-restricted", "inappropriate for some users"),
          "This video is age-restricted, so YouTube needs a signed-in account. " + _SIGN_IN_HELP,
          "This video is age-restricted, so it can't be downloaded here. " + _UPLOAD_INSTEAD),
    _Rule(("private video",), "This video is private."),
    _Rule(("members-only", "join this channel"), "This video is only for channel members."),
    _Rule(("premieres in", "live event will begin"), "This video hasn't been released yet."),
    # Before the generic "not available" rule: these messages also contain "not available".
    _Rule(("javascript runtime", "challenge solving failed", "n challenge", "signature solving failed"),
          "yt-dlp couldn't solve YouTube's player challenge. Install Deno (winget install DenoLand.Deno), "
          "restart StemDeck, and update yt-dlp if it keeps happening.",
          "Couldn't solve YouTube's player check for this video. " + _UPLOAD_INSTEAD),
    _Rule(("requested format is not available", "larger than max-filesize", "max_filesize"),
          "YouTube didn't offer a downloadable audio stream for this video. If this happens for every link, "
          "update yt-dlp (see README) or set up the YouTube sign-in.",
          "YouTube didn't offer a downloadable audio stream for this video. " + _UPLOAD_INSTEAD),
    _Rule(("video unavailable", "video is not available", "available in your country", "has been removed",
           "copyright", "terminated"),
          "This video isn't available (removed, private, or blocked in your country)."),
    # Before the network rule: a 429 also reads "unable to download webpage".
    _Rule(("http error 429", "too many requests"),
          "YouTube is limiting downloads from this network for now. Wait a few minutes and try again.",
          "YouTube is limiting downloads from this server for now. " + _UPLOAD_INSTEAD),
    _Rule(("getaddrinfo", "timed out", "connection refused", "connection reset", "connection aborted",
           "remote end closed", "network is unreachable", "unable to download webpage", "http error 5"),
          "Couldn't reach YouTube. Check your internet connection and try again.",
          "Couldn't reach YouTube. Try again in a minute."),
)


def friendly_error(message: str, *, signed_in: bool, public: bool = False) -> str:
    """Turn a yt-dlp error into one plain sentence for the user (`public`: a visitor of the public site)."""
    lower = message.lower()
    if "not a bot" in lower:  # "Sign in to confirm you're not a bot" (not the age check, which also says "sign in")
        if public:
            return PUBLIC_BLOCKED
        if signed_in:
            return ("YouTube still asks to confirm you're not a bot, so the saved YouTube sign-in has "
                    "probably expired. Export fresh cookies and add them again (YouTube sign-in, home page).")
        return "YouTube wants a sign-in before it allows downloads on this network. " + _SIGN_IN_HELP
    for rule in _ERROR_RULES:
        if any(n in lower for n in rule.needles):
            return (rule.public_text or rule.text) if public else rule.text
    detail = re.sub(r"^(ERROR:\s*)?(\[[^\]]+\]\s*)?([\w-]{11}:\s*)?", "", message.strip())
    return f"YouTube download failed: {detail[:_ERROR_DETAIL_CHARS]}"


# ------------------------------------------------------------------ CLI (used by probe())
USAGE = """usage:

  python -m stemdeck.youtube probe <url>            print the video's title and length as JSON

  python -m stemdeck.youtube set-cookies <file>     save a YouTube sign-in (cookies.txt; youtube.com lines only)

  python -m stemdeck.youtube remove-cookies         remove the saved sign-in

The sign-in is saved in STEMDECK_DATA_DIR (the public site's own data folder when run from its start script)."""


def main() -> None:
    logging.basicConfig(level=logging.WARNING, stream=sys.stderr)
    command = sys.argv[1] if len(sys.argv) > 1 else ""
    if command == "set-cookies" and len(sys.argv) == 3:
        try:
            count = save_cookies(get_settings(), Path(sys.argv[2]).read_bytes())
        except (OSError, YouTubeError) as exc:
            raise SystemExit(f"Not saved: {exc}") from exc
        print(f"Saved {count} youtube.com cookies to {cookies_path(get_settings())} (nothing else was kept).")
        return
    if command == "remove-cookies" and len(sys.argv) == 2:
        delete_cookies(get_settings())
        print("YouTube sign-in removed.")
        return
    if command != "probe" or len(sys.argv) != 3:
        raise SystemExit(USAGE)
    try:
        payload: dict[str, Any] = asdict(fetch_info(canonical_url(sys.argv[2]), get_settings()))
    except YouTubeError as exc:
        payload = {"error": str(exc)}
    print(json.dumps(payload), flush=True)


if __name__ == "__main__":
    main()