Bulk asynchronous downloader for multiple file hosts
Python asynciobunkrcyberdropdownloaderdropboxfilestergofilegoogle-drivemediafiremegamega-nzonedrivepatreonpawchivepinterestpixeldraintransfer-ittwitchtwittervk
refactor: rework aio module (#32)
NTFSvolume057781f84512
diff --git a/cyberdrop_dl/aio.py b/cyberdrop_dl/aio.pynew file mode 100644index 000000000..43a07a6a1--- /dev/null+++ b/cyberdrop_dl/aio.py@@ -0,0 +1,318 @@+"""Async versions of builtins and some path operations"""++from __future__ import annotations++import asyncio+import contextlib+import dataclasses+import shutil+import sys+import tempfile+from abc import ABC, abstractmethod+from pathlib import Path+from stat import S_ISREG+from typing import (+ IO,+ TYPE_CHECKING,+ Any,+ AnyStr,+ Generic,+ ParamSpec,+ Self,+ TypeVar,+ TypeVarTuple,+ cast,+ final,+ overload,+)+from weakref import WeakValueDictionary++from typing_extensions import Sentinel++if TYPE_CHECKING:+ from collections.abc import AsyncGenerator, AsyncIterator, Awaitable, Callable, Coroutine, Iterable, Iterator+ from types import TracebackType++ from _typeshed import OpenBinaryMode, OpenTextMode+++_T = TypeVar("_T")+_Ts = TypeVarTuple("_Ts")+_R = TypeVar("_R")+_P = ParamSpec("_P")+_MISSING = Sentinel("_MISSING")++[email protected](slots=True, eq=False)+class WeakAsyncLocks(Generic[_T]):+ """A WeakValueDictionary wrapper for asyncio.Locks.++ Unused locks are automatically garbage collected. When trying to retrieve a+ lock that does not exists, a new lock will be created.+ """++ _locks: WeakValueDictionary[_T, asyncio.Lock] = dataclasses.field(init=False, default_factory=WeakValueDictionary)++ def __getitem__(self, key: _T, /) -> asyncio.Lock:+ lock = self._locks.get(key)+ if lock is None:+ self._locks[key] = lock = asyncio.Lock()+ return lock++[email protected](slots=True, eq=False)+class AsyncIOWrapper(Generic[AnyStr]):+ """An asynchronous context manager wrapper for a file object."""++ _coro: Awaitable[IO[AnyStr]]+ _io: IO[AnyStr] = dataclasses.field(init=False)++ async def __aenter__(self) -> Self:+ self._io = await self._coro+ return self++ async def __aexit__(self, *_) -> None:+ return await asyncio.to_thread(self._io.close)++ async def __aiter__(self) -> AsyncIterator[AnyStr]:+ while True:+ line = await self.readline()+ if line:+ yield line+ else:+ break++ async def read(self, size: int = -1) -> AnyStr:+ return await asyncio.to_thread(self._io.read, size)++ async def readline(self) -> AnyStr:+ return await asyncio.to_thread(self._io.readline)++ async def readlines(self) -> list[AnyStr]:+ return await asyncio.to_thread(self._io.readlines)++ async def write(self, b: AnyStr, /) -> int:+ return await asyncio.to_thread(self._io.write, b)++ async def writelines(self, lines: Iterable[AnyStr], /) -> None:+ return await asyncio.to_thread(self._io.writelines, lines)++[email protected](slots=True, eq=False)+class AsyncIteratorWrapper(Generic[_T]):+ _coro: Awaitable[Iterable[_T]]+ _iterator: Iterator[_T] | None = dataclasses.field(default=None, init=False)++ def __aiter__(self) -> Self:+ return self++ async def __anext__(self) -> _T:+ if self._iterator is None:+ self._iterator = iter(await self._coro)+ value = await asyncio.to_thread(next, self._iterator, _MISSING)+ if value is _MISSING:+ raise StopAsyncIteration from None++ return cast("_T", value)+++class AsyncContextManagerMixin(ABC):+ __stack: contextlib.AsyncExitStack | None = None++ @final+ @property+ def _stack(self) -> contextlib.AsyncExitStack[bool | None]:+ if self.__stack is None:+ raise RuntimeError(f"{type(self).__name__} can only be used as a context manager")+ return self.__stack++ @final+ async def __aenter__(self) -> Self:+ if self.__stack is not None:+ raise RuntimeError(f"{type(self).__name__} does not allow reentrance")+ self.__stack = contextlib.AsyncExitStack()+ _ = await self.__stack.__aenter__()+ await self._async_ctx_()+ return self++ @final+ async def __aexit__(+ self,+ exc_type: type[BaseException] | None,+ exc_val: BaseException | None,+ exc_tb: TracebackType | None,+ ) -> bool | None:+ return await self._stack.__aexit__(exc_type, exc_val, exc_tb)++ @abstractmethod+ async def _async_ctx_(self) -> None: ...+++async def gather(*coros: Awaitable[_T]) -> list[_T]:+ """Like asyncio.gather but an exception on any coro cancels all pending coros++ AKA: all or nothing"""++ async def run(coro: Awaitable[_R]) -> _R:+ return await coro++ async with asyncio.TaskGroup() as tg:+ tasks = [tg.create_task(run(coro)) for coro in coros]++ return [t.result() for t in tasks]+++async def map(+ coro_factory: Callable[[_T], Awaitable[_R]],+ params: Iterable[_T],+ /,+ *,+ task_limit: int | None = None,+) -> list[_R]:+ """Map an async factory over a sequence of arguments with optional concurrency cap.++ If `task_limit` is given, no more than that many coroutines will be “in flight” at the same time,+ limiting memory pressure and event loop overhead"""+ return await map_tuples(coro_factory, ((param,) for param in params), task_limit=task_limit)+++async def map_tuples(+ coro_factory: Callable[[*_Ts], Awaitable[_R]],+ params_batched: Iterable[tuple[*_Ts]],+ /,+ *,+ task_limit: int | None = None,+) -> list[_R]:+ """Map an async factory over a sequence of arguments with optional concurrency cap.++ If `task_limit` is given, no more than that many coroutines will be “in flight” at the same time,+ limiting memory pressure and event loop overhead"""+ if not task_limit:+ return await gather(*(coro_factory(*params) for params in params_batched))++ semaphore = asyncio.BoundedSemaphore(task_limit)+ tasks: list[asyncio.Task[_R]] = []++ async def run(coro: Awaitable[_R]) -> _R:+ try:+ return await coro+ finally:+ semaphore.release()++ async with asyncio.TaskGroup() as tg:+ for params in params_batched:+ _ = await semaphore.acquire()+ coro = coro_factory(*params)+ tasks.append(tg.create_task(run(coro)))++ return [t.result() for t in tasks]+++def run(coro: Coroutine[Any, Any, _T]) -> _T:+ def _loop_factory() -> asyncio.AbstractEventLoop:+ loop = asyncio.new_event_loop()+ if sys.version_info > (3, 12):+ loop.set_task_factory(asyncio.eager_task_factory)+ return loop++ with asyncio.Runner(loop_factory=_loop_factory) as runner:+ return runner.run(coro)+++def to_thread(fn: Callable[_P, _R]) -> Callable[_P, Coroutine[None, None, _R]]:+ """Convert a blocking callable into an async callable that runs in another thread"""++ async def async_run(*args: _P.args, **kwargs: _P.kwargs) -> _R:+ return await asyncio.to_thread(fn, *args, **kwargs)++ return async_run+++chmod = to_thread(Path.chmod)+copy = to_thread(shutil.copy)+exists = to_thread(Path.exists)+is_dir = to_thread(Path.is_dir)+is_file = to_thread(Path.is_file)+mkdir = to_thread(Path.mkdir)+move = to_thread(shutil.move)+read_bytes = to_thread(Path.read_bytes)+read_text = to_thread(Path.read_text)+resolve = to_thread(Path.resolve)+stat = to_thread(Path.stat)+touch = to_thread(Path.touch)+unlink = remove = to_thread(Path.unlink)+write_bytes = to_thread(Path.write_bytes)+write_text = to_thread(Path.write_text)+++def glob(path: Path, pattern: str) -> AsyncIterator[Path]:+ coro = asyncio.to_thread(path.glob, pattern)+ return AsyncIteratorWrapper(coro)+++def rglob(path: Path, pattern: str) -> AsyncIterator[Path]:+ coro = asyncio.to_thread(path.rglob, pattern)+ return AsyncIteratorWrapper(coro)+++def iterdir(path: Path) -> AsyncIterator[Path]:+ coro = asyncio.to_thread(path.iterdir)+ return AsyncIteratorWrapper(coro)+++@overload+def open(+ path: Path,+ mode: OpenBinaryMode,+ buffering: int = ...,+ encoding: str | None = ...,+ errors: str | None = ...,+ newline: str | None = ...,+) -> AsyncIOWrapper[bytes]: ...+++@overload+def open(+ path: Path,+ mode: OpenTextMode = ...,+ buffering: int = ...,+ encoding: str | None = ...,+ errors: str | None = ...,+ newline: str | None = ...,+) -> AsyncIOWrapper[str]: ...+++def open(+ path: Path,+ mode: str = "r",+ buffering: int = -1,+ encoding: str | None = None,+ errors: str | None = None,+ newline: str | None = None,+) -> AsyncIOWrapper[Any]:+ coro = asyncio.to_thread(path.open, mode, buffering, encoding, errors, newline)+ return AsyncIOWrapper(coro)+++async def get_size(path: Path) -> int | None:+ """If path exists and is a file, returns its size. Returns `None` otherwise"""++ # Manually parse stat result to make sure we only use 1 fs call++ try:+ stat_result = await stat(path)+ except (OSError, ValueError):+ return+ else:+ if not S_ISREG(stat_result.st_mode):+ raise IsADirectoryError(path)+ return stat_result.st_size+++async def temp_dir() -> AsyncGenerator[Path]:+ temp_dir = await asyncio.to_thread(tempfile.TemporaryDirectory, prefix="cdl_", ignore_cleanup_errors=True)+ try:+ yield Path(temp_dir.name)+ finally:+ await asyncio.to_thread(temp_dir.cleanup)diff --git a/cyberdrop_dl/clients/download_client.py b/cyberdrop_dl/clients/download_client.pyindex 738cea3ec..a96a15f0d 100644--- a/cyberdrop_dl/clients/download_client.py+++ b/cyberdrop_dl/clients/download_client.py@@ -10,13 +10,12 @@ from typing import TYPE_CHECKING, Anyimport aiofiles-from cyberdrop_dl import constants+from cyberdrop_dl import aio, constantsfrom cyberdrop_dl.clients.response import AbstractResponsefrom cyberdrop_dl.constants import FILE_FORMATSfrom cyberdrop_dl.data_structures.url_objects import AbsoluteHttpURLfrom cyberdrop_dl.exceptions import DDOSGuardError, DownloadError, InvalidContentTypeError, SlowDownloadError-from cyberdrop_dl.utils import aio, dates-from cyberdrop_dl.utils.aio import WeakAsyncLocks+from cyberdrop_dl.utils import datesfrom cyberdrop_dl.utils.logger import log, log_debugfrom cyberdrop_dl.utils.utilities import get_size_or_none@@ -49,7 +48,7 @@ class DownloadClient:self.manager = managerself.client_manager = client_managerself.download_speed_threshold = self.manager.config_manager.settings_data.runtime_options.slow_download_speed- self._server_locks = WeakAsyncLocks[str]()+ self._server_locks = aio.WeakAsyncLocks[str]()self.server_locked_domains: set[str] = set()self._supports_ranges: bool = Truediff --git a/cyberdrop_dl/crawlers/bunkrr.py b/cyberdrop_dl/crawlers/bunkrr.pyindex 603199ba0..c9a910a01 100644--- a/cyberdrop_dl/crawlers/bunkrr.py+++ b/cyberdrop_dl/crawlers/bunkrr.py@@ -10,11 +10,12 @@ from typing import TYPE_CHECKING, Any, ClassVarfrom aiohttp import ClientConnectorError+from cyberdrop_dl import aiofrom cyberdrop_dl.constants import FILE_FORMATSfrom cyberdrop_dl.crawlers.crawler import Crawler, RateLimit, SupportedPaths, auto_task_idfrom cyberdrop_dl.data_structures.url_objects import AbsoluteHttpURLfrom cyberdrop_dl.exceptions import DDOSGuardError-from cyberdrop_dl.utils import aio, css, open_graph+from cyberdrop_dl.utils import css, open_graphfrom cyberdrop_dl.utils.utilities import error_handling_wrapper, parse_url, xor_decryptif TYPE_CHECKING:diff --git a/cyberdrop_dl/crawlers/hianime.py b/cyberdrop_dl/crawlers/hianime.pyindex 43969c3c0..06c9e1f8a 100644--- a/cyberdrop_dl/crawlers/hianime.py+++ b/cyberdrop_dl/crawlers/hianime.py@@ -6,12 +6,12 @@ from typing import TYPE_CHECKING, Any, ClassVarimport bs4+from cyberdrop_dl.aio import WeakAsyncLocksfrom cyberdrop_dl.crawlers.crawler import Crawler, SupportedPaths, auto_task_idfrom cyberdrop_dl.crawlers.megacloud import MegaCloudCrawlerfrom cyberdrop_dl.data_structures.url_objects import AbsoluteHttpURLfrom cyberdrop_dl.exceptions import ScrapeErrorfrom cyberdrop_dl.utils import css-from cyberdrop_dl.utils.aio import WeakAsyncLocksfrom cyberdrop_dl.utils.utilities import error_handling_wrapperif TYPE_CHECKING:diff --git a/cyberdrop_dl/crawlers/rumble.py b/cyberdrop_dl/crawlers/rumble.pyindex 4e22b72c9..878581bb7 100644--- a/cyberdrop_dl/crawlers/rumble.py+++ b/cyberdrop_dl/crawlers/rumble.py@@ -4,12 +4,13 @@ import dataclassesimport itertoolsfrom typing import TYPE_CHECKING, Any, ClassVar, NamedTuple+from cyberdrop_dl import aiofrom cyberdrop_dl.compat import IntEnumfrom cyberdrop_dl.crawlers.crawler import Crawler, SupportedPathsfrom cyberdrop_dl.data_structures.mediaprops import Resolution, Subtitlefrom cyberdrop_dl.data_structures.url_objects import AbsoluteHttpURLfrom cyberdrop_dl.exceptions import DownloadError, ScrapeError-from cyberdrop_dl.utils import aio, css, m3u8+from cyberdrop_dl.utils import css, m3u8from cyberdrop_dl.utils.utilities import error_handling_wrapper, parse_urlif TYPE_CHECKING:@@ -206,6 +207,6 @@ class RumbleCrawler(Crawler):)if hls_formats:- hls_formats = await aio.gather([resolve_m3u8(f) for f in hls_formats])+ hls_formats = await aio.map(resolve_m3u8, hls_formats)return max((*hls_formats, *other_formats))diff --git a/cyberdrop_dl/downloader/downloader.py b/cyberdrop_dl/downloader/downloader.pyindex 501619041..75620b80c 100644--- a/cyberdrop_dl/downloader/downloader.py+++ b/cyberdrop_dl/downloader/downloader.py@@ -14,7 +14,7 @@ from typing import TYPE_CHECKING, NamedTuple, ParamSpec, TypeVarfrom aiohttp import ClientConnectorError, ClientError, ClientResponseError-from cyberdrop_dl import constants, ffmpeg+from cyberdrop_dl import aio, constants, ffmpegfrom cyberdrop_dl.data_structures.url_objects import HlsSegment, MediaItemfrom cyberdrop_dl.exceptions import (DownloadError,@@ -26,15 +26,12 @@ from cyberdrop_dl.exceptions import (SkipDownloadError,TooManyCrawlerErrors,)-from cyberdrop_dl.utils import aiofrom cyberdrop_dl.utils.logger import log, log_debugfrom cyberdrop_dl.utils.utilities import error_handling_wrapper, parse_url# Windows epoch is January 1, 1601. Unix epoch is January 1, 1970WIN_EPOCH_OFFSET = 116444736e9MAC_OS_SET_FILE = None-_VIDEO_HLS_BATCH_SIZE = 10-_AUDIO_HLS_BATCH_SIZE = 50# Try to import win32con for Windows constants, fallback to hardcoded values if unavailable@@ -249,11 +246,8 @@ class Downloader:if await asyncio.to_thread(output.is_file):return output- batch_size = _VIDEO_HLS_BATCH_SIZE if m3u8.media_type == "video" else _AUDIO_HLS_BATCH_SIZE+ tasks_results = await self._download_segments(media_item, m3u8, download_folder)- tasks_results = await aio.gather(- self._prepare_hls_downloads(media_item, m3u8, download_folder), batch_size=batch_size- )n_successful = sum(1 for result in tasks_results if result.downloaded)if n_successful != n_segmets:@@ -291,9 +285,7 @@ class Downloader:passreturn video, audio, subtitles- def _prepare_hls_downloads(- self, media_item: MediaItem, m3u8: M3U8, download_folder: Path- ) -> list[Coroutine[None, None, SegmentDownloadResult]]:+ def _download_segments(self, media_item: MediaItem, m3u8: M3U8, download_folder: Path):padding = max(5, len(str(len(m3u8.segments))))def create_segments() -> Generator[HlsSegment]:@@ -320,7 +312,11 @@ class Downloader:await self.start_download(seg_media_item),)- return [download_segment(segment) for segment in create_segments()]+ return aio.map(+ download_segment,+ create_segments(),+ task_limit=10 if m3u8.media_type == "video" else 50,+ )async def finalize_download(self, media_item: MediaItem, downloaded: bool) -> None:if downloaded:diff --git a/cyberdrop_dl/managers/client_manager.py b/cyberdrop_dl/managers/client_manager.pyindex 912dc08c4..e425ce9bd 100644--- a/cyberdrop_dl/managers/client_manager.py+++ b/cyberdrop_dl/managers/client_manager.py@@ -15,6 +15,7 @@ from aiohttp import ClientResponse, ClientSessionfrom aiolimiter import AsyncLimiterfrom cyberdrop_dl import constants, ddos_guard, env+from cyberdrop_dl.aio import WeakAsyncLocksfrom cyberdrop_dl.clients.download_client import DownloadClientfrom cyberdrop_dl.clients.flaresolverr import FlareSolverrfrom cyberdrop_dl.clients.response import AbstractResponse@@ -23,7 +24,6 @@ from cyberdrop_dl.data_structures.url_objects import AbsoluteHttpURL, MediaItemfrom cyberdrop_dl.exceptions import DDOSGuardError, DownloadError, ScrapeError, TooManyCrawlerErrorsfrom cyberdrop_dl.ffmpeg import probefrom cyberdrop_dl.ui.prompts.user_prompts import get_cookies_from_browsers-from cyberdrop_dl.utils.aio import WeakAsyncLocksfrom cyberdrop_dl.utils.cookie_management import read_netscape_filesfrom cyberdrop_dl.utils.logger import log, log_debug, log_spacerdiff --git a/cyberdrop_dl/utils/aio.py b/cyberdrop_dl/utils/aio.pydeleted file mode 100644index 222c5dc88..000000000--- a/cyberdrop_dl/utils/aio.py+++ /dev/null@@ -1,98 +0,0 @@-"""Async versions of builtins and some path operations"""--from __future__ import annotations--import asyncio-import weakref-from stat import S_ISREG-from typing import TYPE_CHECKING, Final, Generic, TypeVar, cast--if TYPE_CHECKING:- import pathlib- from collections.abc import Awaitable, Sequence--_T = TypeVar("_T")---if TYPE_CHECKING:- from collections.abc import Awaitable, Sequence---async def gather(coros: Sequence[Awaitable[_T]], batch_size: int = 10) -> list[_T]:- """Like `asyncio.gather`, but creates tasks lazily to minimize event loop overhead.-- This function ensures there are never more than `batch_size` tasks created at any given time.-- If any exception is raised within a task, all currently running tasks- are cancelled and any renaming task in the queue will be ignored.- """-- semaphore = asyncio.BoundedSemaphore(batch_size)- results: list[_T] = cast("list[_T]", [None] * len(coros))-- async def worker(index: int, coro: Awaitable[_T]):- try:- result = await coro- results[index] = result- finally:- semaphore.release()-- async with asyncio.TaskGroup() as tg:- for index, coro in enumerate(coros):- await semaphore.acquire()- tg.create_task(worker(index, coro))-- return results---async def stat(path: pathlib.Path):- return await asyncio.to_thread(path.stat)---async def is_dir(path: pathlib.Path) -> bool:- return await asyncio.to_thread(path.is_dir)---async def is_file(path: pathlib.Path) -> bool:- return await asyncio.to_thread(path.is_file)---async def exists(path: pathlib.Path) -> bool:- return await asyncio.to_thread(path.exists)---async def unlink(path: pathlib.Path, missing_ok: bool = False) -> None:- return await asyncio.to_thread(path.unlink, missing_ok)---async def get_size(path: pathlib.Path) -> int | None:- """If path exists and is a file, returns its size. Returns `None` otherwise"""-- # Manually parse stat result to make sure we only use 1 fs call-- try:- stat_result = await stat(path)- except (OSError, ValueError):- return- else:- if S_ISREG(stat_result.st_mode):- return stat_result.st_size---class WeakAsyncLocks(Generic[_T]):- """A WeakValueDictionary wrapper for asyncio.Locks.-- Unused locks are automatically garbage collected. When trying to retrieve a- lock that does not exists, a new lock will be created.- """-- __slots__ = ("__locks",)-- def __init__(self) -> None:- self.__locks: Final = weakref.WeakValueDictionary[_T, asyncio.Lock]()-- def __getitem__(self, key: _T, /) -> asyncio.Lock:- lock = self.__locks.get(key)- if lock is None:- self.__locks[key] = lock = asyncio.Lock()- return lockdiff --git a/cyberdrop_dl/utils/webhook.py b/cyberdrop_dl/utils/webhook.pyindex a80197348..ed3b001a7 100644--- a/cyberdrop_dl/utils/webhook.py+++ b/cyberdrop_dl/utils/webhook.py@@ -7,8 +7,7 @@ import aiofilesimport richfrom aiohttp import FormData-from cyberdrop_dl import constants-from cyberdrop_dl.utils import aio+from cyberdrop_dl import aio, constantsfrom cyberdrop_dl.utils.logger import log, log_debug, log_spacerif TYPE_CHECKING: