Bulk asynchronous downloader for multiple file hosts
Python asynciobunkrcyberdropdownloaderdropboxfilestergofilegoogle-drivemediafiremegamega-nzonedrivepatreonpawchivepinterestpixeldraintransfer-ittwitchtwittervk
feat: support shorts (Rumble) (#2134)
NTFSvolume8e0e4c620e6f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8773a9639..6438a60d1 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -29,6 +29,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- Support premium URLs (direct links)(GoFile)- BlueSky support- FileditchAlbums support+- Support for shorts (Rumble)### Changeddiff --git a/cyberdrop_dl/crawlers/rumble.py b/cyberdrop_dl/crawlers/rumble.pyindex 0989c04d9..e657c24b1 100644--- a/cyberdrop_dl/crawlers/rumble.py+++ b/cyberdrop_dl/crawlers/rumble.py@@ -1,22 +1,24 @@from __future__ import annotationsimport dataclasses-import itertools+import jsonfrom enum import IntEnum-from typing import TYPE_CHECKING, Any, ClassVar+from typing import TYPE_CHECKING, Any, ClassVar, overridefrom cyberdrop_dl import aiofrom cyberdrop_dl.clients.http import HTTPConfig-from cyberdrop_dl.crawlers.crawler import Crawler, SupportedPaths-from cyberdrop_dl.exceptions import DownloadError, ScrapeError+from cyberdrop_dl.crawlers.crawler import API, Crawler, SupportedPaths+from cyberdrop_dl.exceptions import ScrapeErrorfrom cyberdrop_dl.mediaprops import Resolution, Subtitlefrom cyberdrop_dl.url_objects import AbsoluteHttpURL-from cyberdrop_dl.utils import css, json_ld, m3u8, parse_url+from cyberdrop_dl.utils import css, json_ld, m3u8, parse_url, traversal+from cyberdrop_dl.utils._url import remove_query_paramsfrom cyberdrop_dl.utils.errors import error_handling_wrapperif TYPE_CHECKING:- from collections.abc import AsyncGenerator, Generator, Iterable+ from collections.abc import Generator, Iterable+ import yarlfrom bs4 import BeautifulSoupfrom cyberdrop_dl.url_objects import ScrapeItem@@ -42,7 +44,7 @@ class Metadata:h: int = 0[email protected](slots=True, frozen=True, order=True)[email protected](slots=True, frozen=True, order=True, kw_only=True)class Format:resolution: Resolutionis_single_file: bool # for formats with the same resolution, give priority to non hls@@ -55,68 +57,93 @@ class Format:@dataclasses.dataclass(slots=True, frozen=True)class Video:+ id: strtitle: strupload_date: strurl: AbsoluteHttpURL- best_format: Format+ formats: tuple[Format, ...]subtitles: tuple[Subtitle, ...]+ thumb: str | None = None@HTTPConfig(impersonate="firefox", rate_limit=(8, 1))class RumbleCrawler(Crawler):SUPPORTED_PATHS: ClassVar[SupportedPaths] = {"Channel": "/c/<name>",+ "Channel videos": "/c/<name>/videos",+ "Channel shorts": "/c/<name>/shorts","User": "/user/<name>","Video": "<video_id>-<video-title>.html",+ "Short": "/shorts/<short_id>","Embed": "/embed/<video_id>",}PRIMARY_URL: ClassVar[AbsoluteHttpURL] = AbsoluteHttpURL("https://rumble.com")DOMAIN: ClassVar[str] = "rumble"+ NEXT_PAGE_SELECTOR: ClassVar[str] = "nav a[href*=page]:has(svg[stroke-linecap=round])"++ def __post_init__(self) -> None:+ self.api: RumbleAPI = RumbleAPI.from_crawler(self)async def fetch(self, scrape_item: ScrapeItem) -> None:match scrape_item.url.parts[1:]:case ["embed", video_id] if video_id.startswith("v"):- return await self.embed(scrape_item, video_id)+ await self.embed(scrape_item, video_id)+ case ["shorts", video_id]:+ await self.short(scrape_item, video_id)case [slug] if slug.startswith("v") and slug.endswith(".html"):- return await self.video(scrape_item)- case ["c" | "user", user_name, *_]:- return await self.channel(scrape_item, user_name)+ await self.video(scrape_item)+ case ["c" | "user", user_name, "shorts"]:+ await self.channel_shorts(scrape_item, user_name)+ case ["c" | "user", user_name, "videos"]:+ await self.channel_videos(scrape_item, user_name)+ case ["c" | "user", _user_name]:+ await self.channel(scrape_item)case _:raise ValueError+ @override@classmethoddef transform_url(cls, url: AbsoluteHttpURL) -> AbsoluteHttpURL:- match url.parts[1:]:- case [slug] if slug.startswith("v") and slug.endswith(".html"):- return url.with_query(None)- case _:- return url+ return remove_query_params(super().transform_url(url), keep=("page",))@error_handling_wrapper- async def channel(self, scrape_item: ScrapeItem, name: str) -> None:+ async def channel_shorts(self, scrape_item: ScrapeItem, name: str) -> None:scrape_item.setup_as_album(self.create_title(name))- async for soup in self._pager(scrape_item.url):- from cyberdrop_dl.utils import json_ld+ scrape_item.append_folders("shorts")+ async for soup in self.web_pager(scrape_item.url):+ for short in map(_parse_short, _find_video_objs(soup)):+ new_item = scrape_item.create_child(short.url)+ self.create_eager_task(self._video(new_item, short))+ scrape_item.add_children()++ @override+ @classmethod+ def parse_url(+ cls, url: yarl.URL | str, /, relative_to: AbsoluteHttpURL | None = None, *, trim: bool | None = None+ ) -> AbsoluteHttpURL:+ return remove_query_params(super().parse_url(url, relative_to, trim=trim), keep=("page",))- _, info = json_ld.find(soup, "items", "relative_url")- for item in info["items"]:- if item.get("object_type") != "video":- continue+ @error_handling_wrapper+ async def channel(self, scrape_item: ScrapeItem) -> None:+ for part in ("shorts", "videos"):+ self.create_task(self.run(scrape_item.create_child(scrape_item.url / part)))+ @error_handling_wrapper+ async def channel_videos(self, scrape_item: ScrapeItem, name: str) -> None:+ scrape_item.setup_as_album(self.create_title(name))+ async for soup in self.web_pager(scrape_item.url):+ for item in _find_video_objs(soup):new_item = scrape_item.create_child(self.parse_url(item["url"]))- self.create_task(self.run(new_item, check_referer=True))+ self.create_task(self.video(new_item))scrape_item.add_children()- async def _pager(self, url: AbsoluteHttpURL) -> AsyncGenerator[BeautifulSoup]:- init_page = int(url.query.get("page") or 1)- try:- for page in itertools.count(init_page):- yield await self.request_soup(url.update_query(page=page))+ @error_handling_wrapper+ async def short(self, scrape_item: ScrapeItem, short_id: str) -> None:+ if await self.check_complete_from_referer(scrape_item.url):+ return- except DownloadError as e:- if e.status == 404:- return- raise+ video = await self.api.short(short_id)+ await self._video(scrape_item, video)@error_handling_wrapperasync def video(self, scrape_item: ScrapeItem) -> None:@@ -129,14 +156,21 @@ class RumbleCrawler(Crawler):@error_handling_wrapperasync def embed(self, scrape_item: ScrapeItem, embed_id: str) -> None:- video = await self._get_video_info(embed_id)- best_format = video.best_format+ video = await self.api.embed(embed_id)+ await self._video(scrape_item, video)++ @error_handling_wrapper+ async def _video(self, scrape_item: ScrapeItem, video: Video) -> None:+ if await self.check_complete_from_referer(scrape_item.url):+ return++ best_format = max(await self._resolve_formats(video.formats))if best_format.m3u8:ext = ".mp4"else:_, ext = self.get_filename_and_ext(best_format.url.name)- video_name = self.create_custom_filename(video.title, ext, file_id=embed_id, resolution=best_format.resolution)+ video_name = self.create_custom_filename(video.title, ext, file_id=video.id, resolution=best_format.resolution)scrape_item.uploaded_at = self.parse_iso_date(video.upload_date)scrape_item.url = video.urlself.create_eager_task(@@ -147,33 +181,16 @@ class RumbleCrawler(Crawler):ext,custom_filename=video_name,m3u8=best_format.m3u8,+ thumbnail=video.thumb,))self.handle_subs(scrape_item, video_name, video.subtitles)- async def _get_video_info(self, embed_id: str) -> Video:- api_url = (self.PRIMARY_URL / "embedJS/u3").with_query(request="video", ver=2, v=embed_id)- video: dict[str, Any] = await self.request_json(api_url)-- if video.get("live") == LiveStatus.CURRENTLY_LIVE:- raise ScrapeError(422, "livestreams are not supported")-- formats = _parse_formats(video.get("ua") or {})- subs = _parse_subs(video.get("cc") or {})-- return Video(- upload_date=video["pubDate"],- title=css.unescape(video["title"]),- url=self.parse_url(video["l"]),- best_format=await self._get_best_format(formats),- subtitles=tuple(subs),- )-- async def _get_best_format(self, formats: Iterable[Format]) -> Format:- hls_formats: list[Format] = []- other_formats: list[Format] = [fmt for fmt in formats if fmt.is_single_file or hls_formats.append(fmt)]-+ async def _resolve_formats(self, formats: Iterable[Format]) -> list[Format]:async def resolve_m3u8(fmt: Format) -> Format:+ if fmt.is_single_file:+ return fmt+m3u8, info = await self.request_m3u8_playlist(fmt.url)return dataclasses.replace(fmt,@@ -182,40 +199,112 @@ class RumbleCrawler(Crawler):bitrate=info.stream_info.bandwidth or 0,)- if hls_formats:- hls_formats = await aio.map(resolve_m3u8, hls_formats, task_limit=10)+ return await aio.map(resolve_m3u8, formats, task_limit=10)- return max((*hls_formats, *other_formats))+class RumbleAPI(API):+ async def embed(self, embed_id: str) -> Video:+ api_url = (self.PRIMARY_URL / "embedJS/u3").with_query(request="video", ver=2, v=embed_id)+ data: dict[str, Any] = await self.request_json(api_url)-def _parse_formats(formats: dict[str, list[dict[str, Any]] | dict[str, dict[str, Any]]]) -> Generator[Format]:- for type_, format_options in formats.items():+ if data.get("live") == LiveStatus.CURRENTLY_LIVE:+ raise ScrapeError(422, "livestreams are not supported")++ return Video(+ id=embed_id,+ upload_date=data["pubDate"],+ title=css.unescape(data["title"]),+ url=self.parse_url(data["l"]),+ formats=tuple(_parse_formats(data.get("ua") or {})),+ subtitles=tuple(_parse_subs(data.get("cc") or {})),+ )++ async def short(self, short_id: str) -> Video:+ soup = await self.request_soup(self.PRIMARY_URL / "shorts" / short_id)+ for obj in _find_video_objs(soup):+ if obj.get("permalink_id") == short_id:+ short = obj+ break+ else:+ raise ScrapeError(422, "Unable to find short data")+ return _parse_short(short)+++def _parse_short(short: dict[str, Any]) -> Video:+ return Video(+ id=short["permalink_id"],+ upload_date=short["upload_date"],+ title=css.unescape(short["title"]),+ url=RumbleCrawler.parse_url(short["url"]),+ formats=tuple(_parse_short_formats(short["videos"])),+ subtitles=(),+ thumb=short.get("thumb"),+ )+++def _find_video_objs(soup: BeautifulSoup) -> Generator[dict[str, Any]]:+ for script in css.iselect_text(+ soup,+ selector="script[type='application/json'], script[type='application/ld+json']",+ contains="object_type",+ ):+ for _, obj in traversal.find_objs(+ json.loads(script),+ validate={+ "object_type": "video",+ },+ ):+ yield obj+++def _filter_formats[T](fmts: Iterable[tuple[str, T]]) -> Generator[tuple[FormatType, T]]:+ for type_, fmt in fmts:if type_ in {"audio", "tar", "timeline"}:continuetry:- type_ = FormatType[type_.upper()]+ f_type = FormatType[type_.upper()]except KeyError:raise ScrapeError(422, f"Video has an unknown format type: {type_}") from None- pairs = ((None, f) for f in format_options) if isinstance(format_options, list) else format_options.items()+ yield f_type, fmt+++def _parse_short_formats(formats: Iterable[dict[str, Any]]) -> Generator[Format]:+ for type_, fmt in _filter_formats((fmt["type"], fmt) for fmt in formats):+ is_hls = type_ is FormatType.HLS+ yield Format(+ resolution=Resolution.unknown() if is_hls else Resolution.parse(fmt["resolution"]),+ is_single_file=not is_hls,+ bitrate=fmt.get("bitrate_kbps", 0),+ size=0,+ type=type_,+ url=parse_url(fmt["url"]),+ )- is_single_file = type_ is not FormatType.HLS+def _parse_formats(formats: dict[str, list[dict[str, Any]] | dict[str, dict[str, Any]]]) -> Generator[Format]:+ for type_, format_options in _filter_formats(formats.items()):+ pairs = ((None, f) for f in format_options) if isinstance(format_options, list) else format_options.items()for height, fmt in pairs:- url = parse_url(fmt["url"])meta = Metadata(**(fmt.get("meta") or {}))-if meta.w and meta.h:- resolution = Resolution(meta.w, meta.h)+ res = Resolution(meta.w, meta.h)elif height and height != "auto":- resolution = Resolution.parse(height)+ res = Resolution.parse(height)else:- resolution = Resolution.unknown()-- yield Format(resolution, is_single_file, meta.bitrate, meta.size, type_, url)+ res = Resolution.unknown()++ yield Format(+ resolution=res,+ is_single_file=type_ is not FormatType.HLS,+ bitrate=meta.bitrate,+ size=meta.size,+ type=type_,+ url=parse_url(fmt["url"]),+ )def _parse_subs(subs: dict[str, dict[str, str]]) -> Generator[Subtitle]:diff --git a/cyberdrop_dl/utils/_url.py b/cyberdrop_dl/utils/_url.pyindex bd16fad31..d5301a5e4 100644--- a/cyberdrop_dl/utils/_url.py+++ b/cyberdrop_dl/utils/_url.py@@ -1,6 +1,6 @@from __future__ import annotations-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, castfrom typing_extensions import TypeIs@@ -96,3 +96,7 @@ def matches_any_host(url: yarl.URL, hosts: Iterable[str]) -> bool:def _is_absolute_http_url(url: yarl.URL) -> TypeIs[AbsoluteHttpURL]:return url.absolute and url.scheme in {"http", "https"}+++def remove_query_params[T: yarl.URL](url: T, keep: tuple[str, ...]) -> T:+ return cast("T", url.with_query([(name, value) for name, value in url.query.items() if name in keep] or None))diff --git a/tests/crawlers/test_cases/rumble.py b/tests/crawlers/test_cases/rumble.pyindex 142d8c662..7ff660746 100644--- a/tests/crawlers/test_cases/rumble.py+++ b/tests/crawlers/test_cases/rumble.py@@ -1,10 +1,28 @@DOMAIN = "rumble"TEST_CASES = [+ {+ "url": "https://rumble.com/shorts/v75ijpe",+ "description": "short",+ "results": [+ {+ "url": "re:/video/fww1/1b/s8/2/c/v/9/X/cv9Xz.aaa.mp4",+ "filename": "Why Bad Bunny Was a DISASTER for NFL Fans [v75ijpe][1920p].mp4",+ "debrid_url": None,+ "original_filename": "Why Bad Bunny Was a DISASTER for NFL Fans.mp4",+ "referer": "https://rumble.com/shorts/v75ijpe",+ "album_id": None,+ "uploaded_at": 1770642606,+ "download_folder": "re:Loose Files (Rumble)",+ "thumbnail": "re:/video/fww1/1b/s8/6/c/v/9/X/cv9Xz.adyb.jpg",+ }+ ],+ "count": 1,+ },{"url": "https://rumble.com/vwu8gp-residente-bzrp-music-sessions-49.html?e9s=src_v1_s","results": [{- "url": "https://1a-1791.com/video/s8/2/z/z/A/s/zzAsd.caa.mp4",+ "url": "re:/video/s8/2/z/z/A/s/zzAsd.caa.mp4","filename": "RESIDENTE -- BZRP Music Sessions #49 [vu82er][360p].mp4","original_filename": "RESIDENTE -- BZRP Music Sessions #49.mp4","referer": "https://rumble.com/vwu8gp-residente-bzrp-music-sessions-49.html",@@ -17,19 +35,19 @@ TEST_CASES = ["url": "https://rumble.com/c/RumbleEvents","results": [{- "url": "https://1a-1791.com/video/vo/47ww/m03gQsmi4GE/Px13ulRwHFM.mp4",+ "url": "re:/video/vo/47ww/m03gQsmi4GE/Px13ulRwHFM.mp4","filename": "CLOSING OUT Dave Rubin & Benny Johnson LIVE - Rumble Exclusive Live at TPU [v1at1kt][1080p].mp4","referer": "https://rumble.com/v1df7i1-rumble-exclusive-live-at-tpusa.html","album_id": None,"download_folder": "re:RumbleEvents (Rumble)",},{- "url": "https://1a-1791.com/video/vo/y7pe/dPdI3HbQ11Q/kkxZS05zoL0.mp4",+ "url": "re:/video/vo/y7pe/dPdI3HbQ11Q/kkxZS05zoL0.mp4","filename": "Turning Point USA 2022 Student Action Summit DAY 1 - Rumble Exclusive Liv [v1amumr][1080p].mp4","referer": "https://rumble.com/v1d90jz-rumble-exclusive-live-at-tpusa.html",},{- "url": "https://1a-1791.com/video/vo/5j7n/fsuRaNtWx5A/K9ZKZmzRXAg.mp4",+ "url": "re:/video/vo/5j7n/fsuRaNtWx5A/K9ZKZmzRXAg.mp4","filename": "President Donald J. Trump LIVE at Turning Point - Rumble Exclusive Live at [v1apryd][1080p].mp4","referer": "https://rumble.com/v1dbxvl-rumble-exclusive-live-at-tpusa.html",},