Skip to content

Bulk asynchronous downloader for multiple file hosts

refactor: unify resolution parsing logic (#1285)

NTFSvolumea94a996eddd8
diff --git a/cyberdrop_dl/crawlers/beeg.py b/cyberdrop_dl/crawlers/beeg.py
index c7bf20b7e..65cf3929c 100644
--- a/cyberdrop_dl/crawlers/beeg.py
+++ b/cyberdrop_dl/crawlers/beeg.py
@@ -3,11 +3,10 @@ from __future__ import annotations
from typing import TYPE_CHECKING, Any, ClassVar, NamedTuple
from cyberdrop_dl.crawlers.crawler import Crawler, SupportedPaths
+from cyberdrop_dl.data_structures.mediaprops import Resolution
from cyberdrop_dl.data_structures.url_objects import AbsoluteHttpURL
if TYPE_CHECKING:
- from collections.abc import Iterable
-
from cyberdrop_dl.data_structures.url_objects import ScrapeItem
@@ -17,7 +16,7 @@ M3U8_URL = AbsoluteHttpURL("https://video.beeg.com/")
class Format(NamedTuple):
- heigth: int
+ resolution: Resolution
url: AbsoluteHttpURL
@@ -51,7 +50,7 @@ class BeegComCrawler(Crawler):
scrape_item.possible_datetime = self.parse_iso_date(facts.get("fc_created", ""))
m3u8 = await self.get_m3u8_from_index_url(best_format.url)
filename, ext = self.get_filename_and_ext(best_format.url.name)
- custom_filename = self.create_custom_filename(title, ext, file_id=video_id, resolution=best_format.heigth)
+ custom_filename = self.create_custom_filename(title, ext, file_id=video_id, resolution=best_format.resolution)
await self.handle_file(canonical_url, scrape_item, filename, ext, custom_filename=custom_filename, m3u8=m3u8)
@@ -67,12 +66,12 @@ def get_video_id(url: AbsoluteHttpURL) -> str | None:
def get_best_format(sources: dict[str, str]) -> Format:
- def parse_sources() -> Iterable[tuple[int, str]]:
+ def parse_sources():
for name, uri in sources.items():
try:
- yield int(name.removeprefix("fl_cdn_")), uri
+ yield Resolution.parse(name.removeprefix("fl_cdn_")), uri
except ValueError:
continue
- height, uri = max(parse_sources())
- return Format(height, M3U8_URL / uri)
+ resolution, uri = max(parse_sources())
+ return Format(resolution, M3U8_URL / uri)
diff --git a/cyberdrop_dl/crawlers/crawler.py b/cyberdrop_dl/crawlers/crawler.py
index 7c7006775..ded3a3d9e 100644
--- a/cyberdrop_dl/crawlers/crawler.py
+++ b/cyberdrop_dl/crawlers/crawler.py
@@ -19,6 +19,7 @@ from yarl import URL
from cyberdrop_dl import constants
from cyberdrop_dl.clients.scraper_client import ScraperClient
+from cyberdrop_dl.data_structures.mediaprops import Resolution
from cyberdrop_dl.data_structures.url_objects import AbsoluteHttpURL, MediaItem, ScrapeItem, copy_signature
from cyberdrop_dl.downloader.downloader import Downloader
from cyberdrop_dl.exceptions import MaxChildrenError, NoExtensionError, ScrapeError
@@ -613,9 +614,9 @@ class Crawler(ABC):
@error_handling_wrapper
async def direct_file(self, scrape_item: ScrapeItem, url: URL | None = None, assume_ext: str | None = None) -> None:
- """Download a direct link file. Filename will be extrcation for the url"""
+ """Download a direct link file. Filename will be the url slug"""
link = url or scrape_item.url
- filename, ext = self.get_filename_and_ext(link.name, assume_ext=assume_ext)
+ filename, ext = self.get_filename_and_ext(link.name or link.parent.name, assume_ext=assume_ext)
await self.handle_file(link, scrape_item, filename, ext)
@final
@@ -723,7 +724,7 @@ class Crawler(ABC):
file_id: str | None = None,
video_codec: str | None = None,
audio_codec: str | None = None,
- resolution: m3u8.Resolution | str | int | None = None,
+ resolution: Resolution | str | int | None = None,
hash_string: str | None = None,
only_truncate_stem: bool = True,
) -> str:
@@ -739,19 +740,9 @@ class Crawler(ABC):
extra_info.append(audio_codec)
if _placeholder_config.include_resolution and resolution:
- if isinstance(resolution, m3u8.Resolution):
- resolution = resolution.name
- if isinstance(resolution, str):
- if (digits := resolution.casefold().removesuffix("p")).isdigit():
- extra_info.append(f"{digits}p")
- else:
- resolution_ = next(
- (p for p in VALID_RESOLUTION_NAMES if resolution.casefold() == p.casefold()), None
- )
- assert resolution_, f"Invalid: {resolution = }"
- extra_info.append(resolution_)
- else:
- extra_info.append(f"{resolution}p")
+ if not isinstance(resolution, Resolution):
+ resolution = Resolution.parse(resolution)
+ extra_info.append(resolution.name)
if _placeholder_config.include_hash and hash_string:
assert any(hash_string.startswith(x) for x in HASH_PREFIXES), f"Invalid: {hash_string = }"
diff --git a/cyberdrop_dl/crawlers/eporner.py b/cyberdrop_dl/crawlers/eporner.py
index 8d9a322fa..19ac2c73d 100644
--- a/cyberdrop_dl/crawlers/eporner.py
+++ b/cyberdrop_dl/crawlers/eporner.py
@@ -4,6 +4,7 @@ import dataclasses
from typing import TYPE_CHECKING, ClassVar, NamedTuple
from cyberdrop_dl.crawlers.crawler import Crawler, SupportedPaths
+from cyberdrop_dl.data_structures import Resolution
from cyberdrop_dl.data_structures.url_objects import AbsoluteHttpURL, ScrapeItem
from cyberdrop_dl.exceptions import ScrapeError
from cyberdrop_dl.utils import css
@@ -49,8 +50,8 @@ class Video:
class VideoSource(NamedTuple):
- codec: str # av1 > h264
- resolution: str
+ codec: str # h264 > av1
+ resolution: Resolution
size: str
url: str
@@ -61,7 +62,7 @@ class VideoSource(NamedTuple):
details = name.split("(", 1)[1].removesuffix(")").split(",")
res, codec, size = [d.strip() for d in details]
codec = codec.lower()
- return cls(codec, res, size, link_str)
+ return cls(codec, Resolution.parse(res), size, link_str)
class EpornerCrawler(Crawler):
@@ -201,11 +202,7 @@ def _get_available_sources(soup: BeautifulSoup) -> list[VideoSource]:
def _get_best_src(soup: BeautifulSoup) -> VideoSource:
formats = _get_available_sources(soup)
- for res in RESOLUTIONS:
- sorted_formats = sorted(f for f in formats if f.resolution == res and not f.url.endswith(".m3u8"))
- if sorted_formats:
- return sorted_formats[0]
- raise ScrapeError(422, message="Unable to parse video formats")
+ return max(f for f in formats if f.url.endswith(".m3u8"))
def _parse_video(soup: BeautifulSoup) -> Video:
diff --git a/cyberdrop_dl/crawlers/missav.py b/cyberdrop_dl/crawlers/missav.py
index dfa380aa2..780f50171 100644
--- a/cyberdrop_dl/crawlers/missav.py
+++ b/cyberdrop_dl/crawlers/missav.py
@@ -52,7 +52,7 @@ class MissAVCrawler(Crawler):
m3u8_playlist_url = M3U8_SERVER / uuid / "playlist.m3u8"
m3u8, info = await self.get_m3u8_from_playlist_url(m3u8_playlist_url)
ext = ".mp4"
- filename = self.create_custom_filename(title, ext, resolution=info.resolution.name)
+ filename = self.create_custom_filename(title, ext, resolution=info.resolution)
await self.handle_file(m3u8_playlist_url, scrape_item, filename, ext, m3u8=m3u8)
diff --git a/cyberdrop_dl/crawlers/noodle_magazine.py b/cyberdrop_dl/crawlers/noodle_magazine.py
index 52960b611..1c9bb078f 100644
--- a/cyberdrop_dl/crawlers/noodle_magazine.py
+++ b/cyberdrop_dl/crawlers/noodle_magazine.py
@@ -5,6 +5,7 @@ import json
from typing import TYPE_CHECKING, Any, ClassVar, NamedTuple
from cyberdrop_dl.crawlers.crawler import Crawler, SupportedPaths
+from cyberdrop_dl.data_structures.mediaprops import Resolution
from cyberdrop_dl.data_structures.url_objects import AbsoluteHttpURL
from cyberdrop_dl.exceptions import ScrapeError
from cyberdrop_dl.utils import css
@@ -21,12 +22,12 @@ VIDEOS_SELECTOR = "div#list_videos a.item_link"
class Source(NamedTuple):
- resolution: int
+ resolution: Resolution
file: str
@staticmethod
def new(source_dict: dict[str, Any]) -> Source:
- resolution = int(source_dict["label"])
+ resolution = Resolution.parse(source_dict["label"])
return Source(resolution, source_dict["file"])
diff --git a/cyberdrop_dl/crawlers/odnoklassniki.py b/cyberdrop_dl/crawlers/odnoklassniki.py
index fde93f958..1bf625b6b 100644
--- a/cyberdrop_dl/crawlers/odnoklassniki.py
+++ b/cyberdrop_dl/crawlers/odnoklassniki.py
@@ -4,6 +4,7 @@ import re
from typing import TYPE_CHECKING, Any, ClassVar
from cyberdrop_dl.crawlers.crawler import Crawler, SupportedPaths
+from cyberdrop_dl.data_structures.mediaprops import Resolution
from cyberdrop_dl.data_structures.url_objects import AbsoluteHttpURL
from cyberdrop_dl.exceptions import ScrapeError
from cyberdrop_dl.utils import css, json
@@ -147,20 +148,22 @@ class OdnoklassnikiCrawler(Crawler):
)
-def _get_best_src(metadata: dict[str, Any]) -> tuple[int, str]:
+def _get_best_src(metadata: dict[str, Any]) -> tuple[Resolution, str]:
def parse():
for video in metadata["videos"]:
if not video["disallowed"]:
- resolution = {
- "ultra": 2160,
- "quad": 1440,
- "full": 1080,
- "hd": 720,
- "sd": 480,
- "low": 360,
- "lowest": 240,
- "mobile": 144,
- }[video["name"]]
+ resolution = Resolution.parse(
+ {
+ "ultra": 2160,
+ "quad": 1440,
+ "full": 1080,
+ "hd": 720,
+ "sd": 480,
+ "low": 360,
+ "lowest": 240,
+ "mobile": 144,
+ }[video["name"]]
+ )
yield resolution, video["url"]
return max(parse())
diff --git a/cyberdrop_dl/crawlers/rule34video.py b/cyberdrop_dl/crawlers/rule34video.py
index 13a331373..7ba955c24 100644
--- a/cyberdrop_dl/crawlers/rule34video.py
+++ b/cyberdrop_dl/crawlers/rule34video.py
@@ -5,8 +5,8 @@ import json
from typing import TYPE_CHECKING, ClassVar, NamedTuple
from cyberdrop_dl.crawlers.crawler import Crawler, SupportedPaths
+from cyberdrop_dl.data_structures.mediaprops import Resolution
from cyberdrop_dl.data_structures.url_objects import AbsoluteHttpURL, ScrapeItem
-from cyberdrop_dl.exceptions import ScrapeError
from cyberdrop_dl.utils import css
from cyberdrop_dl.utils.utilities import error_handling_wrapper
@@ -19,7 +19,6 @@ if TYPE_CHECKING:
PRIMARY_URL = AbsoluteHttpURL("https://rule34video.com/")
-RESOLUTIONS = ["4k", "2160p", "1440p", "1080p", "720p", "480p", "360p", "240p"] # best to worst
DOWNLOADS_SELECTOR = "div#tab_video_info div.row_spacer div.wrap > a.tag_item"
JS_SELECTOR = "head > script:contains('uploadDate')"
VIDEO_TITLE_SELECTOR = "h1.title_video"
@@ -46,8 +45,8 @@ class Video:
class VideoSource(NamedTuple):
+ resolution: Resolution
ext: str
- resolution: str
url: str
@@ -111,7 +110,7 @@ def _parse_video(soup: BeautifulSoup) -> Video:
title = css.select_one_get_text(soup, VIDEO_TITLE_SELECTOR)
ld_json = css.select_one_get_text(soup, JS_SELECTOR)
video_data = json.loads(ld_json)
- return Video(title=title, date=video_data["uploadDate"], best_src=_get_best_source(soup))
+ return Video(title=title, date=video_data["uploadDate"], best_src=max(_get_available_sources(soup)))
def _get_available_sources(soup: BeautifulSoup) -> Generator[VideoSource]:
@@ -123,15 +122,7 @@ def _get_available_sources(soup: BeautifulSoup) -> Generator[VideoSource]:
ext = ext.lower()
if ext not in ("mov", "mp4"):
continue
- yield VideoSource(ext, res, url)
-
-
-def _get_best_source(soup: BeautifulSoup) -> VideoSource:
- formats_dict = {v_format.resolution: v_format for v_format in _get_available_sources(soup)}
- for res in RESOLUTIONS:
- if v_format := formats_dict.get(res):
- return v_format
- raise ScrapeError(422, message="Unable to parse video sources")
+ yield VideoSource(Resolution.parse(res), ext, url)
def get_playlist_title(soup: BeautifulSoup, playlist_type: str) -> str:
diff --git a/cyberdrop_dl/crawlers/spankbang.py b/cyberdrop_dl/crawlers/spankbang.py
index 9b47a572d..4c2cfc011 100644
--- a/cyberdrop_dl/crawlers/spankbang.py
+++ b/cyberdrop_dl/crawlers/spankbang.py
@@ -19,7 +19,6 @@ if TYPE_CHECKING:
PRIMARY_URL = AbsoluteHttpURL("https://spankbang.com/")
DEFAULT_QUALITY = "main"
RESOLUTIONS = ["4k", "2160p", "1440p", "1080p", "720p", "480p", "360p", "240p"] # best to worst
-
VIDEO_REMOVED_SELECTOR = "[id='video_removed'], [class*='video_removed']"
VIDEOS_SELECTOR = "div.video-list > div.video-item > a"
diff --git a/cyberdrop_dl/crawlers/xhamster.py b/cyberdrop_dl/crawlers/xhamster.py
index 81f24b441..831dfda6c 100644
--- a/cyberdrop_dl/crawlers/xhamster.py
+++ b/cyberdrop_dl/crawlers/xhamster.py
@@ -7,6 +7,7 @@ import json
from typing import TYPE_CHECKING, Any, ClassVar, NamedTuple
from cyberdrop_dl.crawlers.crawler import Crawler, SupportedPaths
+from cyberdrop_dl.data_structures.mediaprops import Resolution
from cyberdrop_dl.data_structures.url_objects import AbsoluteHttpURL
from cyberdrop_dl.utils.utilities import error_handling_wrapper, get_text_between, parse_url, xor_decrypt
@@ -212,7 +213,7 @@ class XhamsterCrawler(Crawler):
class Format(NamedTuple):
- resolution: int
+ resolution: Resolution
codec: str # h264 > av1
url: AbsoluteHttpURL
@@ -272,7 +273,7 @@ def _parse_http_sources(initials: dict[str, Any]) -> Iterable[Format]:
continue
seen_urls.add(url)
- resolution = int(quality.removesuffix("p"))
+ resolution = Resolution.parse(quality)
yield Format(resolution, codec, url)
@@ -295,12 +296,11 @@ def _parse_xplayer_sources(initials: dict[str, Any]) -> Iterable[Format]:
seen_urls.add(url)
if url.suffix == ".m3u8":
- resolution = 0
+ res = 0
else:
- quality: str = format_dict.get("quality") or format_dict["label"]
- resolution = int(quality.removesuffix("p"))
+ res = format_dict.get("quality") or format_dict["label"]
- yield Format(resolution, codec, url)
+ yield Format(Resolution.parse(res), codec, url)
hls_sources: dict[str, dict[str, str]] = xplayer_sources.get("hls", {})
for codec, format_dict in hls_sources.items():
diff --git a/cyberdrop_dl/data_structures/__init__.py b/cyberdrop_dl/data_structures/__init__.py
index e69de29bb..cb344cf1e 100644
--- a/cyberdrop_dl/data_structures/__init__.py
+++ b/cyberdrop_dl/data_structures/__init__.py
@@ -0,0 +1,13 @@
+from .mediaprops import Codecs, Resolution
+from .url_objects import AbsoluteHttpURL, HlsSegment, MediaItem, QueryDatetimeRange, ScrapeItem, ScrapeItemType
+
+__all__ = [
+ "AbsoluteHttpURL",
+ "Codecs",
+ "HlsSegment",
+ "MediaItem",
+ "QueryDatetimeRange",
+ "Resolution",
+ "ScrapeItem",
+ "ScrapeItemType",
+]
diff --git a/cyberdrop_dl/data_structures/mediaprops.py b/cyberdrop_dl/data_structures/mediaprops.py
new file mode 100644
index 000000000..2b46bdb4a
--- /dev/null
+++ b/cyberdrop_dl/data_structures/mediaprops.py
@@ -0,0 +1,120 @@
+from __future__ import annotations
+
+import re
+from fractions import Fraction
+from typing import TYPE_CHECKING, Final, NamedTuple
+
+if TYPE_CHECKING:
+ from collections.abc import Iterable
+
+ import yarl
+
+
+VIDEO_CODECS = "avc1", "avc2", "avc3", "avc4", "av1", "hevc", "hev1", "hev2", "hvc1", "hvc2", "vp8", "vp9", "vp10"
+AUDIO_CODECS = "ac-3", "ec-3", "mp3", "mp4a", "opus", "vorbis"
+
+
+class Codecs(NamedTuple):
+ video: str | None
+ audio: str | None
+
+ @staticmethod
+ def parse(codecs: str | None) -> Codecs:
+ if not codecs:
+ return Codecs(None, None)
+ video_codec = audio_codec = None
+
+ def match_codec(codec: str, lookup_array: Iterable[str]) -> str | None:
+ codec, *_ = codec.split(".")
+ clean_codec = codec[:-1].replace("0", "") + codec[-1]
+ return next((key for key in lookup_array if clean_codec.startswith(key)), None)
+
+ for codec in codecs.split(","):
+ if not video_codec and (found := match_codec(codec, VIDEO_CODECS)):
+ video_codec = found
+ elif not audio_codec and (found := match_codec(codec, AUDIO_CODECS)):
+ audio_codec = found
+ if video_codec and audio_codec:
+ break
+
+ assert video_codec
+ if "avc" in video_codec:
+ video_codec = "avc1"
+ elif "hev" in video_codec or "hvc" in video_codec:
+ video_codec = "hevc"
+ return Codecs(video_codec, audio_codec)
+
+
+class Resolution(NamedTuple):
+ width: int
+ height: int
+
+ @property
+ def name(self) -> str:
+ if 7600 < self.width < 8200:
+ return "8K"
+ if 3800 < self.width < 4100:
+ return "4K"
+ return f"{self.height}p"
+
+ @property
+ def aspect_ratio(self) -> Fraction:
+ return Fraction(self.width, self.height)
+
+ @staticmethod
+ def parse(url_number_or_string: yarl.URL | str | int, /) -> Resolution:
+ if isinstance(url_number_or_string, int):
+ return Resolution._from_height(url_number_or_string)
+
+ if not isinstance(url_number_or_string, str):
+ for resolution in COMMON_RESOLUTIONS:
+ if str(resolution.height) in url_number_or_string.parts:
+ return resolution
+
+ url_number_or_string = url_number_or_string.path
+
+ # "1080p", "720i", "480P", the most common case
+ if (height := url_number_or_string.rstrip("pPiI")).isdecimal():
+ return Resolution._from_height(height)
+
+ # "1920x1080", "1280X720" or "640,480"
+ if match := re.search(r"(?P<width>\d+)[xX,](?P<height>\d+)", url_number_or_string):
+ return Resolution(
+ width=int(match.group("width")),
+ height=int(match.group("height")),
+ )
+
+ # "1080p", "720i", "480P" w regex, slower but works with substrings
+ if match := re.search(r"(?<![a-zA-Z0-9])(\d+)[pPiI](?![a-zA-Z0-9])", url_number_or_string):
+ return Resolution._from_height(match.group(1))
+
+ # "2K", "4K", "8K"
+ if match := re.search(r"\b([248])[kK]\b", url_number_or_string):
+ height = {"2": 1440, "4": 2160, "8": 4320}[match.group(1)]
+ return Resolution._from_height(height)
+
+ raise ValueError(f"Unable to parse resolution from {url_number_or_string}")
+
+ @staticmethod
+ def _from_height(height: str | int, aspect_ratio: float = 16 / 9) -> Resolution:
+ height = int(height)
+ width = round(height * aspect_ratio)
+ return Resolution(width, height)
+
+
+COMMON_RESOLUTIONS: Final = tuple(
+ Resolution(*resolution) # Best to worst
+ for resolution in (
+ (7680, 4320),
+ (3840, 2160),
+ (2560, 1440),
+ (1920, 1080),
+ (1280, 720),
+ (640, 480),
+ (640, 360),
+ (480, 320),
+ (426, 240),
+ (320, 240),
+ (256, 144),
+ )
+)
diff --git a/cyberdrop_dl/utils/m3u8.py b/cyberdrop_dl/utils/m3u8.py
index cda10f948..466d1f96d 100644
--- a/cyberdrop_dl/utils/m3u8.py
+++ b/cyberdrop_dl/utils/m3u8.py
@@ -1,16 +1,15 @@
from __future__ import annotations
-import re
from dataclasses import dataclass
from datetime import timedelta
from enum import StrEnum
-from fractions import Fraction
from functools import cached_property
from typing import TYPE_CHECKING, NamedTuple
from m3u8 import M3U8 as _M3U8
from m3u8 import Media, Playlist
+from cyberdrop_dl.data_structures.mediaprops import Codecs, Resolution
from cyberdrop_dl.utils.utilities import parse_url
if TYPE_CHECKING:
@@ -21,85 +20,6 @@ if TYPE_CHECKING:
from cyberdrop_dl.data_structures.url_objects import AbsoluteHttpURL
-RESOLUTION_REGEX = [
- re.compile(regex)
- for regex in [
- r"(?P<width>\d+)x(?P<height>\d+)", # ex: 1920x1080
- r"(?P<height_p>\d+)p", # ex: 1080p, 720p
- ]
-]
-
-
-VIDEO_CODECS = "avc1", "avc2", "avc3", "avc4", "av1", "hevc", "hev1", "hev2", "hvc1", "hvc2", "vp8", "vp9", "vp10"
-AUDIO_CODECS = "ac-3", "ec-3", "mp3", "mp4a", "opus", "vorbis"
-
-
-class Codecs(NamedTuple):
- video: str | None
- audio: str | None
-
- @staticmethod
- def parse(codecs: str | None) -> Codecs:
- if not codecs:
- return Codecs(None, None)
- video_codec = audio_codec = None
-
- def codec_or_none(codec: str, lookup_array: Iterable[str]) -> str | None:
- codec, *_ = codec.split(".")
- clean_codec = codec[:-1].replace("0", "") + codec[-1]
- return next((key for key in lookup_array if clean_codec.startswith(key)), None)
-
- for codec in codecs.split(","):
- if not video_codec and (found := codec_or_none(codec, VIDEO_CODECS)):
- video_codec = found
- elif not audio_codec and (found := codec_or_none(codec, AUDIO_CODECS)):
- audio_codec = found
- if video_codec and audio_codec:
- break
-
- assert video_codec
- if "avc" in video_codec:
- video_codec = "avc1"
- elif "hev" in video_codec or "hvc" in video_codec:
- video_codec = "hevc"
- return Codecs(video_codec, audio_codec)
-
-
-class Resolution(NamedTuple):
- width: int
- height: int
-
- @property
- def name(self) -> str:
- if 7600 < self.width < 8200:
- return "8K"
- if 3800 < self.width < 4100:
- return "4K"
- return f"{self.height}p"
-
- @property
- def aspect_ratio(self) -> Fraction:
- return Fraction(self.width, self.height)
-
-
-RESOLUTIONS = [
- Resolution(*resolution) # Best to worst
- for resolution in [
- (7680, 4320),
- (3840, 2160),
- (2560, 1440),
- (1920, 1080),
- (1280, 720),
- (640, 480),
- (640, 360),
- (480, 320),
- (426, 240),
- (320, 240),
- (256, 144),
- ]
-]
-
-
class MediaType(StrEnum):
audio = "AUDIO"
video = "VIDEO"
@@ -246,23 +166,7 @@ def get_resolution_from_url(url: AbsoluteHttpURL | str) -> Resolution:
if isinstance(url, str):
url = parse_url(url, trim=False) # Raises Invalid URL error for relative URLs
- for resolution in RESOLUTIONS:
- if str(resolution.height) in url.parts:
- return resolution
-
- for pattern in RESOLUTION_REGEX:
- if match := re.search(pattern, url.path):
- try:
- width = int(match.group("width"))
- height = int(match.group("height"))
- return Resolution(width, height)
- except (IndexError, KeyError):
- height_ = match.groupdict().get("height_p")
- if not height_:
- continue
-
- height = int(height_)
- width = round(height * 16 / 9) # Assume 16:9 aspect ratio
- return Resolution(width, height)
-
- raise RuntimeError("Unable to parse resolution")
+ try:
+ return Resolution.parse(url)
+ except ValueError:
+ raise RuntimeError(f"Unable to parse resolution from {url}") from None