mirror of
https://github.com/rommapp/romm.git
synced 2026-11-28 17:48:31 +01:00
fix(launchbox): read the YouTube id from watch URLs wherever v sits and without a fragment (#5764)
* fix(launchbox): read the YouTube id from watch URLs wherever v sits and without a fragment A video URL with v after another parameter yielded no id, and a #t= fragment was kept as part of it. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> * fix(launchbox): ignore a trailer URL that cannot be parsed Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> * pr-ready: code-review Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * pr-ready: simplify Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * pr-ready: review-polish Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(metadata): share one YouTube id parser across LaunchBox, Demozoo and Pouet LaunchBox now also reads ids from embed, shorts, live, /v/ and youtube-nocookie links, and Demozoo and Pouet now accept URLs without a scheme. Ids are checked against the 11-character format at parse time. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com> Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com>
This commit is contained in:
@@ -11,15 +11,16 @@ from __future__ import annotations
|
||||
import re
|
||||
from collections.abc import Mapping, Sequence
|
||||
from typing import Any, Final, NotRequired, TypedDict
|
||||
from urllib.parse import parse_qs, urlencode, urlparse
|
||||
from urllib.parse import urlencode, urlparse
|
||||
|
||||
from config import DEMOZOO_API_KEY
|
||||
from logger.logger import log
|
||||
from utils import int_or_none, valid_youtube_id
|
||||
from utils import int_or_none
|
||||
from utils.datetime import parse_utc_timestamp
|
||||
from utils.platform_slugs import UniversalPlatformSlug as UPS
|
||||
from utils.platform_slugs import fill_duplicate_slugs
|
||||
from utils.rate_limiter import RateLimiter
|
||||
from utils.urls import youtube_id_from_url
|
||||
|
||||
from .base_handler import (
|
||||
BaseRom,
|
||||
@@ -91,29 +92,6 @@ def demozoo_id_from_url(value: str) -> int | None:
|
||||
return int_or_none(match.group(1)) if match else None
|
||||
|
||||
|
||||
def _youtube_id_from_url(url: str) -> str | None:
|
||||
if not url:
|
||||
return None
|
||||
parsed = urlparse(url.strip())
|
||||
host = parsed.netloc.lower().removeprefix("www.")
|
||||
if host in {"youtu.be", "m.youtu.be"}:
|
||||
return valid_youtube_id(parsed.path.lstrip("/").split("/", 1)[0])
|
||||
if host not in {
|
||||
"youtube.com",
|
||||
"m.youtube.com",
|
||||
"music.youtube.com",
|
||||
"youtube-nocookie.com",
|
||||
}:
|
||||
return None
|
||||
qs = parse_qs(parsed.query)
|
||||
if qs.get("v"):
|
||||
return valid_youtube_id(qs["v"][0])
|
||||
parts = [p for p in parsed.path.split("/") if p]
|
||||
if len(parts) >= 2 and parts[0] in {"embed", "shorts", "v", "live", "e"}:
|
||||
return valid_youtube_id(parts[1])
|
||||
return None
|
||||
|
||||
|
||||
def _pouet_id_from_url(url: str) -> int | None:
|
||||
if "which=" not in url:
|
||||
return None
|
||||
@@ -414,7 +392,7 @@ def production_to_rom(data: dict[str, Any]) -> DemozooRom:
|
||||
from handler.metadata.csdb_handler import csdb_id_from_url
|
||||
|
||||
csdb_id = csdb_id_from_url(url)
|
||||
vid = _youtube_id_from_url(url)
|
||||
vid = youtube_id_from_url(url)
|
||||
if vid and youtube_id is None:
|
||||
youtube_id = vid
|
||||
if cls not in {"PouetProduction", "CsdbRelease"}:
|
||||
|
||||
@@ -9,6 +9,7 @@ from handler.filesystem.base_handler import region_name_to_provider_shortcode
|
||||
from handler.metadata.ss_handler import get_preferred_media_types
|
||||
from utils.database import safe_str_to_bool
|
||||
from utils.html_text import html_to_text
|
||||
from utils.urls import youtube_id_from_url
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from models.rom import Rom
|
||||
@@ -31,7 +32,6 @@ from .utils import (
|
||||
parse_list,
|
||||
parse_playmode,
|
||||
parse_release_date,
|
||||
parse_videourl,
|
||||
sanitize_filename,
|
||||
)
|
||||
|
||||
@@ -693,7 +693,7 @@ def build_launchbox_metadata(
|
||||
"max_players": max_players,
|
||||
"release_type": release_type,
|
||||
"cooperative": cooperative,
|
||||
"youtube_video_id": parse_videourl(video_url),
|
||||
"youtube_video_id": youtube_id_from_url(video_url) or "",
|
||||
"community_rating": community_rating,
|
||||
"community_rating_count": community_rating_count,
|
||||
"wikipedia_url": wikipedia_url,
|
||||
|
||||
@@ -171,15 +171,3 @@ def parse_playmode(play_mode: str | None) -> bool:
|
||||
return False
|
||||
pm = play_mode.lower()
|
||||
return bool(re.search(r"\b(cooperative|coop|co-op)\b", pm))
|
||||
|
||||
|
||||
def parse_videourl(url: str | None) -> str:
|
||||
if not url:
|
||||
return ""
|
||||
|
||||
if "youtube.com/watch?v=" in url:
|
||||
return url.split("v=")[-1].split("&")[0]
|
||||
elif "youtu.be/" in url:
|
||||
return url.split("/")[-1].split("?")[0]
|
||||
|
||||
return ""
|
||||
|
||||
@@ -19,6 +19,7 @@ from logger.logger import log
|
||||
from utils import get_version, int_or_none
|
||||
from utils.context import ctx_httpx_client
|
||||
from utils.rate_limiter import RateLimiter
|
||||
from utils.urls import youtube_id_from_url
|
||||
|
||||
from .base_handler import (
|
||||
BaseRom,
|
||||
@@ -29,7 +30,6 @@ from .base_handler import (
|
||||
from .demozoo_handler import (
|
||||
DEMOZOO_PROD_PAGE,
|
||||
_append_unique,
|
||||
_youtube_id_from_url,
|
||||
build_scene_summary,
|
||||
format_credit_line,
|
||||
http_url,
|
||||
@@ -234,11 +234,11 @@ def production_to_rom(prod: dict[str, Any]) -> PouetRom:
|
||||
kind = str(link.get("type") or "").strip().lower()
|
||||
if "soundtrack" in kind:
|
||||
_append_unique(soundtrack_urls, href)
|
||||
vid = _youtube_id_from_url(href)
|
||||
vid = youtube_id_from_url(href)
|
||||
if vid and youtube_id is None:
|
||||
youtube_id = vid
|
||||
if youtube_id is None:
|
||||
youtube_id = _youtube_id_from_url(str(prod.get("download") or ""))
|
||||
youtube_id = youtube_id_from_url(str(prod.get("download") or ""))
|
||||
|
||||
csdb = int_or_none(prod.get("csdb"))
|
||||
if csdb:
|
||||
|
||||
@@ -13,7 +13,6 @@ from handler.metadata import demozoo_handler
|
||||
from handler.metadata.demozoo_handler import (
|
||||
DemozooHandler,
|
||||
_pouet_id_from_url,
|
||||
_youtube_id_from_url,
|
||||
build_scene_summary,
|
||||
demozoo_id_from_url,
|
||||
extract_demozoo_id_from_filename,
|
||||
@@ -758,21 +757,6 @@ class TestProductionRows:
|
||||
assert meta.get("download_urls") == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("url", "video_id"),
|
||||
[
|
||||
("https://youtu.be/dQw4w9WgXcQ", "dQw4w9WgXcQ"),
|
||||
("https://www.youtube.com/embed/dQw4w9WgXcQ", "dQw4w9WgXcQ"),
|
||||
("https://youtube.com/shorts/dQw4w9WgXcQ", "dQw4w9WgXcQ"),
|
||||
("https://www.youtube.com/user/futurecrew", None),
|
||||
("https://vimeo.com/123", None),
|
||||
("", None),
|
||||
],
|
||||
)
|
||||
def test_youtube_id_from_url(url: str, video_id: str | None):
|
||||
assert _youtube_id_from_url(url) == video_id
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("url", "pouet_id"),
|
||||
[
|
||||
|
||||
@@ -56,7 +56,6 @@ from handler.metadata.launchbox_handler.utils import (
|
||||
launchbox_region_to_shortcode,
|
||||
parse_playmode,
|
||||
parse_release_date,
|
||||
parse_videourl,
|
||||
sanitize_filename,
|
||||
)
|
||||
from handler.redis_handler import async_cache
|
||||
@@ -292,32 +291,6 @@ class TestParsePlaymode:
|
||||
assert parse_playmode("") is False
|
||||
|
||||
|
||||
class TestParseVideourl:
|
||||
def test_youtube_watch(self):
|
||||
assert (
|
||||
parse_videourl("https://www.youtube.com/watch?v=dQw4w9WgXcQ")
|
||||
== "dQw4w9WgXcQ"
|
||||
)
|
||||
|
||||
def test_youtube_watch_with_extra_params(self):
|
||||
assert parse_videourl("https://www.youtube.com/watch?v=abc123&t=30") == "abc123"
|
||||
|
||||
def test_youtu_be(self):
|
||||
assert parse_videourl("https://youtu.be/dQw4w9WgXcQ") == "dQw4w9WgXcQ"
|
||||
|
||||
def test_youtu_be_with_query(self):
|
||||
assert parse_videourl("https://youtu.be/abc123?t=30") == "abc123"
|
||||
|
||||
def test_non_youtube(self):
|
||||
assert parse_videourl("https://vimeo.com/123456") == ""
|
||||
|
||||
def test_none(self):
|
||||
assert parse_videourl(None) == ""
|
||||
|
||||
def test_empty(self):
|
||||
assert parse_videourl("") == ""
|
||||
|
||||
|
||||
# ===========================================================================
|
||||
# TestPlatforms
|
||||
# ===========================================================================
|
||||
@@ -1058,9 +1031,9 @@ class TestBuildLaunchboxMetadata:
|
||||
assert meta.get("cooperative", None) is True
|
||||
|
||||
def test_youtube_video_id_extracted(self):
|
||||
local = {"VideoUrl": "https://www.youtube.com/watch?v=abc123"}
|
||||
local = {"VideoUrl": "https://www.youtube.com/watch?v=dQw4w9WgXcQ"}
|
||||
meta = build_launchbox_metadata(local=local, remote=None, images=[])
|
||||
assert meta.get("youtube_video_id", None) == "abc123"
|
||||
assert meta.get("youtube_video_id", None) == "dQw4w9WgXcQ"
|
||||
|
||||
def test_companies_deduplicated(self):
|
||||
local = {"Developer": "Nintendo", "Publisher": "Nintendo"}
|
||||
|
||||
@@ -10,6 +10,7 @@ from utils.urls import (
|
||||
rom_content_url,
|
||||
rom_id_from_content_url,
|
||||
romfile_content_url,
|
||||
youtube_id_from_url,
|
||||
)
|
||||
|
||||
REQUEST = Request(
|
||||
@@ -83,3 +84,37 @@ def test_get_public_base_url(
|
||||
) -> None:
|
||||
mocker.patch("utils.urls.config.ROMM_BASE_URL", base_url)
|
||||
assert get_public_base_url() == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("url", "video_id"),
|
||||
[
|
||||
("https://www.youtube.com/watch?v=dQw4w9WgXcQ", "dQw4w9WgXcQ"),
|
||||
("https://www.youtube.com/watch?v=dQw4w9WgXcQ&t=30", "dQw4w9WgXcQ"),
|
||||
("https://www.youtube.com/watch?feature=share&v=dQw4w9WgXcQ", "dQw4w9WgXcQ"),
|
||||
("https://www.youtube.com/watch?v=dQw4w9WgXcQ#t=30", "dQw4w9WgXcQ"),
|
||||
("https://m.youtube.com/watch?v=dQw4w9WgXcQ", "dQw4w9WgXcQ"),
|
||||
("https://youtu.be/dQw4w9WgXcQ", "dQw4w9WgXcQ"),
|
||||
("https://youtu.be/dQw4w9WgXcQ?t=30", "dQw4w9WgXcQ"),
|
||||
("https://youtu.be/dQw4w9WgXcQ#t=30", "dQw4w9WgXcQ"),
|
||||
("https://www.youtu.be/dQw4w9WgXcQ", "dQw4w9WgXcQ"),
|
||||
("https://www.youtube.com/embed/dQw4w9WgXcQ", "dQw4w9WgXcQ"),
|
||||
("https://youtube.com/shorts/dQw4w9WgXcQ", "dQw4w9WgXcQ"),
|
||||
("https://www.youtube.com/live/dQw4w9WgXcQ", "dQw4w9WgXcQ"),
|
||||
("https://www.youtube.com/v/dQw4w9WgXcQ", "dQw4w9WgXcQ"),
|
||||
("https://www.youtube-nocookie.com/embed/dQw4w9WgXcQ", "dQw4w9WgXcQ"),
|
||||
("www.youtube.com/watch?v=dQw4w9WgXcQ", "dQw4w9WgXcQ"),
|
||||
("youtube.com/watch?v=dQw4w9WgXcQ", "dQw4w9WgXcQ"),
|
||||
("youtu.be/dQw4w9WgXcQ", "dQw4w9WgXcQ"),
|
||||
(" https://youtu.be/dQw4w9WgXcQ ", "dQw4w9WgXcQ"),
|
||||
("https://www.youtube.com/watch?v=abc123", None),
|
||||
("https://www.youtube.com/user/futurecrew", None),
|
||||
("https://youtu.be/", None),
|
||||
("https://[youtube.com/watch?v=dQw4w9WgXcQ", None),
|
||||
("https://vimeo.com/123456", None),
|
||||
("", None),
|
||||
(None, None),
|
||||
],
|
||||
)
|
||||
def test_youtube_id_from_url(url: str | None, video_id: str | None) -> None:
|
||||
assert youtube_id_from_url(url) == video_id
|
||||
|
||||
@@ -3,16 +3,23 @@ from __future__ import annotations
|
||||
import ipaddress
|
||||
import re
|
||||
from typing import TYPE_CHECKING, Final
|
||||
from urllib.parse import quote, urlsplit
|
||||
from urllib.parse import parse_qs, quote, urlsplit
|
||||
|
||||
import yarl
|
||||
from fastapi import Request
|
||||
|
||||
import config
|
||||
from utils import valid_youtube_id
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from models.rom import Rom, RomFile
|
||||
|
||||
YOUTUBE_HOSTS: Final = frozenset(
|
||||
{"youtube.com", "m.youtube.com", "music.youtube.com", "youtube-nocookie.com"}
|
||||
)
|
||||
YOUTUBE_SHORT_HOSTS: Final = frozenset({"youtu.be", "m.youtu.be"})
|
||||
YOUTUBE_ID_PATH_PREFIXES: Final = frozenset({"embed", "shorts", "v", "live", "e"})
|
||||
|
||||
# The tail of the get_rom_content route, matched whatever host or root path served it.
|
||||
ROM_CONTENT_PATH_RE: Final = re.compile(r"/api/roms/(\d+)/content/[^/]*$")
|
||||
|
||||
@@ -69,3 +76,28 @@ def rom_id_from_content_url(value: str) -> int | None:
|
||||
return None
|
||||
match = ROM_CONTENT_PATH_RE.search(parts.path)
|
||||
return int(match.group(1)) if match else None
|
||||
|
||||
|
||||
def youtube_id_from_url(url: str | None) -> str | None:
|
||||
"""The video id in a YouTube URL, or None for anything else."""
|
||||
url = (url or "").strip()
|
||||
if not url:
|
||||
return None
|
||||
try:
|
||||
parts = urlsplit(url)
|
||||
# Provider data can omit the scheme.
|
||||
if not parts.netloc:
|
||||
parts = urlsplit(f"//{url}")
|
||||
host = (parts.hostname or "").removeprefix("www.")
|
||||
except ValueError:
|
||||
return None
|
||||
segments = [s for s in parts.path.split("/") if s]
|
||||
if host in YOUTUBE_SHORT_HOSTS:
|
||||
return valid_youtube_id(segments[0]) if segments else None
|
||||
if host not in YOUTUBE_HOSTS:
|
||||
return None
|
||||
if video_ids := parse_qs(parts.query).get("v"):
|
||||
return valid_youtube_id(video_ids[0])
|
||||
if len(segments) >= 2 and segments[0] in YOUTUBE_ID_PATH_PREFIXES:
|
||||
return valid_youtube_id(segments[1])
|
||||
return None
|
||||
|
||||
Reference in New Issue
Block a user