Files
yt-recommender/app/youtube.py
2026-12-03 02:08:44 +11:00

173 lines
5.8 KiB
Python

"""Read your YouTube data with yt-dlp (using cookies) and public RSS feeds.
No Google API key or OAuth is needed: History and Watch Later aren't
available through the official API, so everything goes through yt-dlp.
"""
import logging
import re
import time
import xml.etree.ElementTree as ET
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime
import requests
from yt_dlp import YoutubeDL
from . import config
log = logging.getLogger(__name__)
FEED_HISTORY = "https://www.youtube.com/feed/history"
FEED_WATCH_LATER = "https://www.youtube.com/playlist?list=WL"
FEED_SUBSCRIPTIONS = "https://www.youtube.com/feed/subscriptions"
FEED_CHANNELS = "https://www.youtube.com/feed/channels"
RSS_URL = "https://www.youtube.com/feeds/videos.xml?channel_id={}"
ATOM = {
"a": "http://www.w3.org/2005/Atom",
"yt": "http://www.youtube.com/xml/schemas/2015",
"media": "http://search.yahoo.com/mrss/",
}
VIDEO_ID = re.compile(r"^[A-Za-z0-9_-]{11}$")
class CookieError(RuntimeError):
pass
def _ydl_opts(limit: int, use_cookies: bool = True) -> dict:
opts = {
"extract_flat": "in_playlist",
"skip_download": True,
"quiet": True,
"no_warnings": True,
"ignoreerrors": True,
"playlistend": limit,
"lazy_playlist": True,
"sleep_interval_requests": 1, # be gentle with your account
}
if use_cookies:
if not config.COOKIES_FILE.exists():
raise CookieError(
f"cookies file not found at {config.COOKIES_FILE}. "
"See README: 'Export your YouTube cookies'."
)
opts["cookiefile"] = str(config.COOKIES_FILE)
return opts
def _flat(url: str, limit: int, use_cookies: bool = True) -> list[dict]:
with YoutubeDL(_ydl_opts(limit, use_cookies)) as ydl:
info = ydl.extract_info(url, download=False)
if not info:
return []
return [e for e in (info.get("entries") or []) if e][:limit]
def _normalise(entry: dict, source: str) -> dict | None:
vid = entry.get("id")
if not vid or not VIDEO_ID.match(vid):
return None
url = entry.get("url") or ""
duration = entry.get("duration")
ts = entry.get("timestamp") or entry.get("release_timestamp")
return {
"id": vid,
"title": entry.get("title"),
"channel": entry.get("channel") or entry.get("uploader"),
"channel_id": entry.get("channel_id") or entry.get("uploader_id"),
"description": entry.get("description") or "",
"duration": int(duration) if duration else None,
"published": int(ts) if ts else None,
"is_short": "/shorts/" in url,
"source": source,
}
def _clean(entries: list[dict], source: str) -> list[dict]:
out = []
for e in entries:
v = _normalise(e, source)
if v:
out.append(v)
return out
def check_cookies() -> bool:
"""True if the cookies give a signed-in session (History is readable)."""
try:
return bool(_flat(FEED_HISTORY, 1))
except Exception as exc: # noqa: BLE001
log.warning("cookie check failed: %s", exc)
return False
def fetch_history(limit: int = config.HISTORY_LIMIT) -> list[dict]:
return _clean(_flat(FEED_HISTORY, limit), "history")
def fetch_watch_later(limit: int = config.WATCH_LATER_LIMIT) -> list[dict]:
return _clean(_flat(FEED_WATCH_LATER, limit), "watch_later")
def fetch_subscription_feed(limit: int = config.SUBS_FEED_LIMIT) -> list[dict]:
return _clean(_flat(FEED_SUBSCRIPTIONS, limit), "subs")
def fetch_subscribed_channels() -> list[dict]:
chans = []
for e in _flat(FEED_CHANNELS, 2000):
cid = e.get("channel_id") or e.get("id")
if cid and cid.startswith("UC"):
chans.append({"channel_id": cid, "name": e.get("channel") or e.get("title")})
return chans
def _rss_one(channel_id: str) -> list[dict]:
try:
r = requests.get(RSS_URL.format(channel_id), timeout=15)
if r.status_code != 200:
return []
root = ET.fromstring(r.content)
except Exception: # noqa: BLE001
return []
out = []
for e in root.findall("a:entry", ATOM):
vid = e.findtext("yt:videoId", namespaces=ATOM)
link = e.find("a:link", ATOM)
href = link.get("href", "") if link is not None else ""
pub = e.findtext("a:published", namespaces=ATOM)
group = e.find("media:group", ATOM)
desc = group.findtext("media:description", namespaces=ATOM) if group is not None else ""
out.append({
"id": vid,
"title": e.findtext("a:title", namespaces=ATOM),
"channel": e.findtext("a:author/a:name", namespaces=ATOM),
"channel_id": channel_id,
"description": (desc or "")[:1000],
"duration": None,
"published": int(datetime.fromisoformat(pub).timestamp()) if pub else None,
"is_short": "/shorts/" in href,
"source": "rss",
})
return [v for v in out if v["id"]]
def fetch_rss(channel_ids: list[str], workers: int = 8) -> list[dict]:
"""Latest ~15 uploads per channel with publish dates. No cookies, no quota."""
with ThreadPoolExecutor(max_workers=workers) as pool:
results = pool.map(_rss_one, channel_ids)
return [v for batch in results for v in batch]
def search_recent(query: str, limit: int = config.DISCOVERY_PER_QUERY) -> list[dict]:
"""Newest search results for a topic (discovery outside your subscriptions)."""
try:
entries = _flat(f"ytsearchdate{limit}:{query}", limit, use_cookies=False)
except Exception as exc: # noqa: BLE001
log.warning("search %r failed: %s", query, exc)
return []
# Search results usually have no exact upload date; the pipeline fills it
# from the channel's RSS feed. Undated videos are never recommended.
return _clean(entries, "discovery")