40 lines
1.4 KiB
Python
40 lines
1.4 KiB
Python
import json
|
|
import re
|
|
import urllib.parse
|
|
import urllib.request
|
|
|
|
VIDEO_ID_PATTERN = re.compile(r"^[\w-]{11}$")
|
|
YOUTUBE_HOSTS = {"youtube.com", "www.youtube.com", "m.youtube.com", "music.youtube.com", "youtu.be"}
|
|
PATH_PREFIXES = ("/shorts/", "/embed/", "/live/")
|
|
|
|
|
|
def video_id(text: str) -> str | None:
|
|
text = text.strip()
|
|
if VIDEO_ID_PATTERN.match(text):
|
|
return text
|
|
|
|
url = urllib.parse.urlparse(text if "://" in text else f"https://{text}")
|
|
if url.hostname not in YOUTUBE_HOSTS:
|
|
return None
|
|
if url.hostname == "youtu.be":
|
|
candidate = url.path.strip("/").split("/")[0]
|
|
elif url.path == "/watch":
|
|
candidate = urllib.parse.parse_qs(url.query).get("v", [""])[0]
|
|
else:
|
|
prefix = next((prefix for prefix in PATH_PREFIXES if url.path.startswith(prefix)), None)
|
|
candidate = url.path[len(prefix):].split("/")[0] if prefix else ""
|
|
return candidate if VIDEO_ID_PATTERN.match(candidate) else None
|
|
|
|
|
|
def watch_url(identifier: str) -> str:
|
|
return f"https://music.youtube.com/watch?v={identifier}"
|
|
|
|
|
|
def video_title(identifier: str) -> str | None:
|
|
query = urllib.parse.urlencode({"url": f"https://www.youtube.com/watch?v={identifier}", "format": "json"})
|
|
try:
|
|
with urllib.request.urlopen(f"https://www.youtube.com/oembed?{query}", timeout=10) as response:
|
|
return json.load(response).get("title")
|
|
except (OSError, ValueError):
|
|
return None
|