Inline YouTube Music embeds with one shared embed spec
YouTube Music has no player of its own and music.youtube.com sends X-Frame-Options SAMEORIGIN, so music links render YouTube's own player with an Open in YouTube Music caption. Tracks, playlists and OLAK5uy albums embed; browse, channel, search and library stay plain links. - embeds.py is the single URL spec (exact host allowlists, query-order independent, validated ids only); embed-spec.js is generated from it by the embeds-sync CLI command and drift is tested - rendering.py and ContentRenderer.js both follow it; the old duplicate YouTube regexes are removed - max 3 music embeds per content item, overflow stays a plain link - fixes evilyoutube.com matching and watch?feature=share&v=ID links - fixes the invalid unicode CSS escape that printed u2197 after every external link in rendered content - docs, privacy third-party row, parser table tests, server/client parity Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,163 @@
|
||||
# retoor <retoor@molodetz.nl>
|
||||
|
||||
import json
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from urllib.parse import parse_qs, urlencode, urlparse
|
||||
|
||||
EMBED_JS_PATH = Path(__file__).parent / "static" / "js" / "embed-spec.js"
|
||||
|
||||
YOUTUBE_HOSTS = frozenset(
|
||||
{
|
||||
"youtube.com",
|
||||
"www.youtube.com",
|
||||
"m.youtube.com",
|
||||
"youtube-nocookie.com",
|
||||
"www.youtube-nocookie.com",
|
||||
}
|
||||
)
|
||||
MUSIC_HOSTS = frozenset({"music.youtube.com"})
|
||||
SHORT_HOSTS = frozenset({"youtu.be", "www.youtu.be"})
|
||||
|
||||
VIDEO_ID_PATTERN = "[A-Za-z0-9_-]{11}"
|
||||
LIST_ID_PATTERN = "[A-Za-z0-9_-]{13,64}"
|
||||
START_PATTERN = "[0-9]{1,6}s?"
|
||||
MAX_START_SECONDS = 86400
|
||||
MAX_MUSIC_EMBEDS = 3
|
||||
|
||||
EMBED_BASE = "https://www.youtube.com/embed"
|
||||
PLAYLIST_SLUG = "videoseries"
|
||||
EMBED_ALLOW = (
|
||||
"accelerometer; autoplay; clipboard-write; encrypted-media; "
|
||||
"gyroscope; picture-in-picture"
|
||||
)
|
||||
MUSIC_CAPTION = "Open in YouTube Music"
|
||||
PATH_VIDEO_PREFIXES = ("embed", "v", "shorts")
|
||||
|
||||
_VIDEO_ID_RE = re.compile(VIDEO_ID_PATTERN)
|
||||
_LIST_ID_RE = re.compile(LIST_ID_PATTERN)
|
||||
_START_RE = re.compile(START_PATTERN)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Embed:
|
||||
kind: str
|
||||
video_id: str
|
||||
list_id: str
|
||||
start: int
|
||||
music: bool
|
||||
|
||||
|
||||
class EmbedParser:
|
||||
@staticmethod
|
||||
def parse(url: str) -> Embed | None:
|
||||
try:
|
||||
parts = urlparse(url)
|
||||
except ValueError:
|
||||
return None
|
||||
if parts.scheme not in ("http", "https"):
|
||||
return None
|
||||
host = (parts.hostname or "").lower()
|
||||
query = parse_qs(parts.query)
|
||||
segments = [segment for segment in parts.path.split("/") if segment]
|
||||
start = EmbedParser._start(query)
|
||||
if host in SHORT_HOSTS:
|
||||
if len(segments) != 1 or not _VIDEO_ID_RE.fullmatch(segments[0]):
|
||||
return None
|
||||
return Embed("video", segments[0], "", start, False)
|
||||
music = host in MUSIC_HOSTS
|
||||
if not music and host not in YOUTUBE_HOSTS:
|
||||
return None
|
||||
list_id = EmbedParser._list_id(query)
|
||||
if segments == ["watch"]:
|
||||
return EmbedParser._from_watch(query, list_id, start, music)
|
||||
if segments == ["playlist"]:
|
||||
return EmbedParser._playlist(list_id, music)
|
||||
if music:
|
||||
return None
|
||||
if segments == ["embed"] and query.get("listType", [""])[0] == "playlist":
|
||||
return EmbedParser._playlist(list_id, False)
|
||||
if len(segments) == 2 and segments[0] in PATH_VIDEO_PREFIXES:
|
||||
return EmbedParser._from_path(segments, list_id, start)
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def src(embed: Embed) -> str:
|
||||
if embed.kind == "playlist":
|
||||
return f"{EMBED_BASE}/{PLAYLIST_SLUG}?{urlencode({'list': embed.list_id})}"
|
||||
params: dict[str, str | int] = {}
|
||||
if embed.list_id:
|
||||
params["list"] = embed.list_id
|
||||
if embed.start:
|
||||
params["start"] = embed.start
|
||||
suffix = f"?{urlencode(params)}" if params else ""
|
||||
return f"{EMBED_BASE}/{embed.video_id}{suffix}"
|
||||
|
||||
@staticmethod
|
||||
def spec() -> dict:
|
||||
return {
|
||||
"youtubeHosts": sorted(YOUTUBE_HOSTS),
|
||||
"musicHosts": sorted(MUSIC_HOSTS),
|
||||
"shortHosts": sorted(SHORT_HOSTS),
|
||||
"videoIdPattern": VIDEO_ID_PATTERN,
|
||||
"listIdPattern": LIST_ID_PATTERN,
|
||||
"startPattern": START_PATTERN,
|
||||
"maxStartSeconds": MAX_START_SECONDS,
|
||||
"maxMusicEmbeds": MAX_MUSIC_EMBEDS,
|
||||
"embedBase": EMBED_BASE,
|
||||
"playlistSlug": PLAYLIST_SLUG,
|
||||
"allow": EMBED_ALLOW,
|
||||
"musicCaption": MUSIC_CAPTION,
|
||||
"pathVideoPrefixes": list(PATH_VIDEO_PREFIXES),
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def write_module(path: Path = EMBED_JS_PATH) -> int:
|
||||
spec = EmbedParser.spec()
|
||||
body = json.dumps(spec, ensure_ascii=False, sort_keys=True, indent=4)
|
||||
path.write_text(
|
||||
f"// retoor <retoor@molodetz.nl>\n\nexport const EMBED_SPEC = {body};\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
return len(spec)
|
||||
|
||||
@staticmethod
|
||||
def _first(query: dict, key: str) -> str:
|
||||
values = query.get(key)
|
||||
return values[0] if values else ""
|
||||
|
||||
@staticmethod
|
||||
def _list_id(query: dict) -> str:
|
||||
value = EmbedParser._first(query, "list")
|
||||
return value if _LIST_ID_RE.fullmatch(value) else ""
|
||||
|
||||
@staticmethod
|
||||
def _start(query: dict) -> int:
|
||||
raw = EmbedParser._first(query, "start") or EmbedParser._first(query, "t")
|
||||
if not _START_RE.fullmatch(raw):
|
||||
return 0
|
||||
seconds = int(raw.rstrip("s"))
|
||||
return seconds if seconds <= MAX_START_SECONDS else 0
|
||||
|
||||
@staticmethod
|
||||
def _playlist(list_id: str, music: bool) -> Embed | None:
|
||||
if not list_id:
|
||||
return None
|
||||
return Embed("playlist", "", list_id, 0, music)
|
||||
|
||||
@staticmethod
|
||||
def _from_watch(query: dict, list_id: str, start: int, music: bool) -> Embed | None:
|
||||
video_id = EmbedParser._first(query, "v")
|
||||
if _VIDEO_ID_RE.fullmatch(video_id):
|
||||
return Embed("video", video_id, list_id, start, music)
|
||||
return EmbedParser._playlist(list_id, music)
|
||||
|
||||
@staticmethod
|
||||
def _from_path(segments: list[str], list_id: str, start: int) -> Embed | None:
|
||||
slug = segments[1]
|
||||
if slug == PLAYLIST_SLUG:
|
||||
return EmbedParser._playlist(list_id, False)
|
||||
if not _VIDEO_ID_RE.fullmatch(slug):
|
||||
return None
|
||||
return Embed("video", slug, list_id, start, False)
|
||||
Reference in New Issue
Block a user