Bulk asynchronous downloader for multiple file hosts
Python asynciobunkrcyberdropdownloaderdropboxfilestergofilegoogle-drivemediafiremegamega-nzonedrivepatreonpawchivepinterestpixeldraintransfer-ittwitchtwittervk
refactor: ban asyncio.gather
NTFSvolume9b1be3008b91
diff --git a/cyberdrop_dl/aio.py b/cyberdrop_dl/aio.pyindex 71c1f4ce5..ac50b58bb 100644--- a/cyberdrop_dl/aio.py+++ b/cyberdrop_dl/aio.py@@ -265,7 +265,7 @@ async def safe_gather[T1, T2, T3](This makes errors deterministic"""coros = filter(None, (coro_1, coro_2, coro_3))- results = await asyncio.gather(*coros, return_exceptions=True)+ results = await asyncio.gather(*coros, return_exceptions=True) # noqa: TID251errors = tuple(r for r in results if isinstance(r, BaseException))if errors:raise BaseExceptionGroup("", errors)diff --git a/cyberdrop_dl/cookies.py b/cyberdrop_dl/cookies.pyindex 8dfd4e883..a7d4947a4 100644--- a/cyberdrop_dl/cookies.py+++ b/cyberdrop_dl/cookies.py@@ -9,6 +9,7 @@ from http.cookiejar import Cookie, CookieJar, MozillaCookieJarfrom http.cookies import CookieError, SimpleCookiefrom typing import TYPE_CHECKING, Final+from cyberdrop_dl import aiofrom cyberdrop_dl.dependencies import browser_cookie3if TYPE_CHECKING:@@ -101,7 +102,7 @@ def split(extracted_cookies: Iterable[Cookie]) -> dict[str, MozillaCookieJar]:async def export(cookies: Iterable[Cookie], output_path: Path) -> None:cookie_jars = split(cookies)await asyncio.to_thread(output_path.mkdir, parents=True, exist_ok=True)- _ = await asyncio.gather(+ _ = await aio.gather(*(asyncio.to_thread(cj.save,@@ -118,7 +119,7 @@ async def read_netscape_files(cookie_files: Sequence[Path]) -> AsyncGenerator[Sinow = int(time.time())all_domains: set[str] = set()duplicates: set[str] = set()- for cookie_jar in await asyncio.gather(*(asyncio.to_thread(_read_netscape_file, file) for file in cookie_files)):+ for cookie_jar in await aio.gather(*(asyncio.to_thread(_read_netscape_file, file) for file in cookie_files)):if not cookie_jar:continuediff --git a/cyberdrop_dl/crawlers/_hls.py b/cyberdrop_dl/crawlers/_hls.pyindex 06dc30b0b..dee7a463e 100644--- a/cyberdrop_dl/crawlers/_hls.py+++ b/cyberdrop_dl/crawlers/_hls.py@@ -1,13 +1,12 @@from __future__ import annotations-import asyncioimport dataclassesimport loggingimport osfrom abc import ABC, abstractmethodfrom typing import TYPE_CHECKING, Literal, override-from cyberdrop_dl import ffmpeg+from cyberdrop_dl import aio, ffmpegfrom cyberdrop_dl.exceptions import DownloadErrorfrom cyberdrop_dl.utils import m3u8@@ -71,7 +70,7 @@ class HLSMixin(ABC):return Nonereturn await self._request_m3u8(url, headers, media_type)- video, audio, subs = await asyncio.gather(+ video, audio, subs = await aio.safe_gather(*(resolve(url, name)for name, url in zip(diff --git a/cyberdrop_dl/crawlers/hianime.py b/cyberdrop_dl/crawlers/hianime.pyindex 146231aa0..43bf650cf 100644--- a/cyberdrop_dl/crawlers/hianime.py+++ b/cyberdrop_dl/crawlers/hianime.py@@ -1,11 +1,11 @@from __future__ import annotations-import asyncioimport dataclassesfrom typing import TYPE_CHECKING, Any, ClassVarimport bs4+from cyberdrop_dl import aiofrom cyberdrop_dl.aio import WeakAsyncLocksfrom cyberdrop_dl.crawlers.crawler import Crawler, SupportedPaths, auto_task_idfrom cyberdrop_dl.crawlers.megacloud import MegaCloudCrawler@@ -114,7 +114,7 @@ class HiAnimeCrawler(Crawler):async def _request_anime_info(self, web_url: AbsoluteHttpURL, anime_id: int) -> Anime:episodes_url = web_url.origin() / "ajax/v2/episode/list/" / str(anime_id)- anime_soup, episodes_resp = await asyncio.gather(+ anime_soup, episodes_resp = await aio.safe_gather(self.request_soup(web_url),self.request_json(episodes_url),)diff --git a/cyberdrop_dl/crawlers/mixdrop.py b/cyberdrop_dl/crawlers/mixdrop.pyindex 5f3e0104c..fed2ee413 100644--- a/cyberdrop_dl/crawlers/mixdrop.py+++ b/cyberdrop_dl/crawlers/mixdrop.py@@ -1,8 +1,8 @@from __future__ import annotations-import asynciofrom typing import TYPE_CHECKING, ClassVar+from cyberdrop_dl import aiofrom cyberdrop_dl.crawlers.crawler import Crawler, SupportedDomains, SupportedPathsfrom cyberdrop_dl.url_objects import AbsoluteHttpURLfrom cyberdrop_dl.utils import css, error_handling_wrapper, js_unpacker@@ -58,7 +58,7 @@ class MixDropCrawler(Crawler):video_url = self.PRIMARY_URL / "f" / file_idembed_url = self.PRIMARY_URL / "e" / file_id- soup, embed_html = await asyncio.gather(self.request_soup(video_url), self.request_text(embed_url))+ soup, embed_html = await aio.safe_gather(self.request_soup(video_url), self.request_text(embed_url))title = css.select_text(soup, "div.tbl-c.title b")md_props = dict(_extract_properties(embed_html))return title, self.parse_url(md_props["wurl"])diff --git a/cyberdrop_dl/downloader/hls.py b/cyberdrop_dl/downloader/hls.pyindex 54b6622b0..3afb3eda4 100644--- a/cyberdrop_dl/downloader/hls.py+++ b/cyberdrop_dl/downloader/hls.py@@ -132,7 +132,7 @@ async def _merge_segments(seg_paths: Sequence[Path], output: Path, media_type: sawait ffmpeg.merge_subs(seg_paths, output)return- ffmpeg_result = await ffmpeg.concat(seg_paths, output, same_folder=False)+ ffmpeg_result = await ffmpeg.concat(seg_paths, output)if not ffmpeg_result.success:raise DownloadError("FFmpeg Concat Error", ffmpeg_result.stderr)diff --git a/cyberdrop_dl/ffmpeg.py b/cyberdrop_dl/ffmpeg.pyindex 57a2e2668..26b1c0b40 100644--- a/cyberdrop_dl/ffmpeg.py+++ b/cyberdrop_dl/ffmpeg.py@@ -14,6 +14,7 @@ from typing import TYPE_CHECKING, Any, Literal, Self, TypedDictfrom multidict import CIMultiDict, CIMultiDictProxy+from cyberdrop_dl import aiofrom cyberdrop_dl.utils import DictDataclassif TYPE_CHECKING:@@ -92,7 +93,7 @@ def ffprobe_version() -> str | None:async def merge(input_files: Iterable[Path], output_file: Path) -> SubProcessResult:result = await _merge(input_files, output_file)if result.success:- await _delete_files(input_files, same_folder=False)+ await aio.gather(*map(_try_delete, input_files))return result@@ -102,13 +103,13 @@ async def _merge(input_files: Iterable[Path], output_file: Path) -> SubProcessRereturn await _run_command(command)-async def concat(input_files: Iterable[Path], output_file: Path, *, same_folder: bool = True) -> SubProcessResult:+async def concat(input_files: Iterable[Path], output_file: Path) -> SubProcessResult:concat_file = output_file.with_suffix(output_file.suffix + ".ffmpeg_concat.txt")await _create_concat_file(input_files, output_file=concat_file)try:result = await _concat(concat_file, output_file)if result.success:- await _delete_files(input_files, same_folder=same_folder)+ await aio.gather(*map(_try_delete, input_files))finally:await _try_delete(concat_file)@@ -148,20 +149,11 @@ async def _fixup_concat_video(input_file: Path, output_file: Path) -> SubProcessasync def _try_delete(file: Path) -> None:try:- await asyncio.to_thread(file.unlink, missing_ok=True)+ await aio.unlink(file, missing_ok=True)except OSError as e:logger.warning(f"Unable to delete '{file}' {e}")-async def _delete_files(files: Iterable[Path], *, same_folder: bool) -> None:- if same_folder:- folder = next(iter(files)).parent- logger.debug("Deleting all files inside '%s'", folder)- await asyncio.to_thread(shutil.rmtree, folder, ignore_errors=True)- else:- _ = await asyncio.gather(*map(_try_delete, files))--async def merge_subs(files: Iterable[Path], output: Path) -> None:logger.debug("Merging subs to '%s'", output)await asyncio.to_thread(_raw_concat, files, output)diff --git a/cyberdrop_dl/hasher.py b/cyberdrop_dl/hasher.pyindex 6feda4db8..8722ccbce 100644--- a/cyberdrop_dl/hasher.py+++ b/cyberdrop_dl/hasher.py@@ -213,7 +213,7 @@ class Hasher:if await aio.is_file(item.path):return item- results = await asyncio.gather(+ results = await aio.gather(*(exists(item) for item in self.manager.completed_downloads if item.id not in self._hashed_items))for media_item in results:diff --git a/cyberdrop_dl/storage/_psutil.py b/cyberdrop_dl/storage/_psutil.pyindex 5be6ad437..d384c9deb 100644--- a/cyberdrop_dl/storage/_psutil.py+++ b/cyberdrop_dl/storage/_psutil.py@@ -137,10 +137,7 @@ async def start_loop() -> None:if not mountpoints:return- usage = await asyncio.gather(- *(asyncio.to_thread(_disk_usage, mount) for mount in mountpoints),- return_exceptions=False,- )+ usage = await asyncio.gather(*(asyncio.to_thread(_disk_usage, mount) for mount in mountpoints))_free_space.update(zip(mountpoints, usage, strict=True))last_check = -1diff --git a/cyberdrop_dl/utils/apprise.py b/cyberdrop_dl/utils/apprise.pyindex bed8187bc..358f3efba 100644--- a/cyberdrop_dl/utils/apprise.py+++ b/cyberdrop_dl/utils/apprise.py@@ -73,7 +73,7 @@ async def send_notifications(urls: Sequence[AppriseURL], body: str) -> None:async def _notify(apprise_obj: apprise.Apprise, messages: Iterable[_AppriseMessage]) -> None:with borrow_logger("apprise", level=logging.INFO):- _ = await asyncio.gather(+ _ = await aio.gather(*(apprise_obj.async_notify(title=msg.title,diff --git a/pyproject.toml b/pyproject.tomlindex 9eaeeb899..5dce962aa 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -169,6 +169,9 @@ ignore = [[tool.ruff.lint.flake8-boolean-trap]extend-allowed-calls = ["cyberdrop_dl.logs._enter_context"]+[tool.ruff.lint.flake8-tidy-imports.banned-api]+"asyncio.gather".msg = "Use aio.gather or aio.safe_gather instead"+[tool.ruff.lint.per-file-ignores]"**/{tests,docs,scripts}/*" = ["E402", # imports not at the top of the file.