Skip to content

Bulk asynchronous downloader for multiple file hosts

refactor: replace asyncio.to_thread calls with aio calls (#110)

NTFSvolume7005760b849b
diff --git a/cyberdrop_dl/aio.py b/cyberdrop_dl/aio.py
index 43a07a6a1..ab15b729e 100644
--- a/cyberdrop_dl/aio.py
+++ b/cyberdrop_dl/aio.py
@@ -243,6 +243,7 @@ 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)
+rmdir = to_thread(Path.rmdir)
def glob(path: Path, pattern: str) -> AsyncIterator[Path]:
diff --git a/cyberdrop_dl/clients/download_client.py b/cyberdrop_dl/clients/download_client.py
index df46926c2..3748c4373 100644
--- a/cyberdrop_dl/clients/download_client.py
+++ b/cyberdrop_dl/clients/download_client.py
@@ -119,10 +119,10 @@ class DownloadClient:
media_item: MediaItem,
domain: str,
resume_point: int,
- resp: aiohttp.ClientResponse | AbstractResponse,
+ resp: aiohttp.ClientResponse | AbstractResponse[Any],
) -> bool:
if resp.status == HTTPStatus.REQUESTED_RANGE_NOT_SATISFIABLE:
- await asyncio.to_thread(media_item.partial_file.unlink)
+ await aio.unlink(media_item.partial_file)
await self.client_manager.check_http_status(resp, download=True)
@@ -147,7 +147,7 @@ class DownloadClient:
return False
if resp.status != HTTPStatus.PARTIAL_CONTENT:
- await asyncio.to_thread(media_item.partial_file.unlink, missing_ok=True)
+ await aio.unlink(media_item.partial_file, missing_ok=True)
if (
not media_item.is_segment
@@ -254,13 +254,11 @@ class DownloadClient:
await self._post_download_check(media_item)
- def _pre_download_check(self, media_item: MediaItem) -> Coroutine[Any, Any, None]:
- def prepare() -> None:
- media_item.partial_file.parent.mkdir(parents=True, exist_ok=True)
- if not media_item.partial_file.is_file():
- media_item.partial_file.touch()
-
- return asyncio.to_thread(prepare)
+ @aio.to_thread
+ def _pre_download_check(self, media_item: MediaItem) -> None:
+ media_item.partial_file.parent.mkdir(parents=True, exist_ok=True)
+ if not media_item.partial_file.is_file():
+ media_item.partial_file.touch()
async def _post_download_check(self, media_item: MediaItem, *_) -> None:
if not await aio.get_size(media_item.partial_file):
@@ -298,13 +296,13 @@ class DownloadClient:
downloaded = await self._download(domain, media_item)
if downloaded:
- await asyncio.to_thread(media_item.partial_file.rename, media_item.path)
+ await aio.move(media_item.partial_file, media_item.path)
if not media_item.is_segment:
proceed = await self.client_manager.check_file_duration(media_item)
await self.manager.database.history.add_duration(domain, media_item)
if not proceed:
logger.info(f"Download skipped {media_item.url} due to runtime restrictions")
- await asyncio.to_thread(media_item.path.unlink)
+ await aio.unlink(media_item.path)
await self.mark_incomplete(media_item, domain)
self.manager.progress_manager.download_progress.add_skipped()
return False
@@ -331,7 +329,7 @@ class DownloadClient:
async def add_file_size(self, domain: str, media_item: MediaItem) -> None:
if not media_item.path:
media_item.path = self.get_file_location(media_item)
- if await asyncio.to_thread(media_item.path.is_file):
+ if await aio.is_file(media_item.path):
await self.manager.database.history.add_filesize(domain, media_item)
async def handle_media_item_completion(self, media_item: MediaItem, downloaded: bool = False) -> None:
diff --git a/cyberdrop_dl/clients/hash_client.py b/cyberdrop_dl/clients/hash_client.py
index 6b47a0375..10c421fc6 100644
--- a/cyberdrop_dl/clients/hash_client.py
+++ b/cyberdrop_dl/clients/hash_client.py
@@ -59,9 +59,9 @@ class HashClient:
self.manager.live_manager.get_hash_live(stop=True),
self.manager.progress_manager.hash_progress.currently_hashing_dir(path),
):
- if not await asyncio.to_thread(path.is_dir):
+ if not await aio.is_dir(path):
raise NotADirectoryError
- for file in path.rglob("*"):
+ async for file in aio.rglob(path, "*"):
_ = await self.update_db_and_retrive_hash(file)
async def hash_item(self, media_item: MediaItem) -> None:
@@ -141,7 +141,7 @@ class HashClient:
async def save_hash_data(self, media_item: MediaItem, hash: str | None) -> None:
if not hash:
return
- absolute_path = await asyncio.to_thread(media_item.path.resolve)
+ absolute_path = await aio.resolve(media_item.path)
size = await aio.get_size(media_item.path)
assert size
self.hashed_media_items.append(media_item)
@@ -203,7 +203,7 @@ class HashClient:
downloads = self.manager.completed_downloads
async def exists(item: MediaItem) -> MediaItem | None:
- if await asyncio.to_thread(item.path.is_file):
+ if await aio.is_file(item.path):
return item
results = await asyncio.gather(*(exists(item) for item in downloads))
@@ -225,7 +225,7 @@ async def _delete_file(path: Path, to_trash: bool = True) -> bool:
if to_trash:
coro = asyncio.to_thread(send2trash, path)
else:
- coro = asyncio.to_thread(path.unlink)
+ coro = aio.unlink(path)
try:
await coro
diff --git a/cyberdrop_dl/downloader/downloader.py b/cyberdrop_dl/downloader/downloader.py
index a3b6aac75..1ee803259 100644
--- a/cyberdrop_dl/downloader/downloader.py
+++ b/cyberdrop_dl/downloader/downloader.py
@@ -10,7 +10,6 @@ import sys
from dataclasses import field
from datetime import datetime
from functools import wraps
-from pathlib import Path
from typing import TYPE_CHECKING, NamedTuple, ParamSpec, TypeVar
from aiohttp import ClientConnectorError, ClientError, ClientResponseError
@@ -61,6 +60,7 @@ elif sys.platform == "darwin":
if TYPE_CHECKING:
from collections.abc import Callable, Coroutine, Generator
+ from pathlib import Path
from cyberdrop_dl.clients.download_client import DownloadClient
from cyberdrop_dl.managers.manager import Manager
@@ -211,7 +211,7 @@ class Downloader:
media_item.set_task_id(task_id)
video, audio, _subs = await self._download_rendition_group(media_item, m3u8_group)
if not audio:
- await asyncio.to_thread(video.rename, media_item.path)
+ await aio.move(video, media_item.path)
else:
# TODO: add remux method to ffmpeg to create an mkv file instead of mp4
# Subtitles format may be incompatible with mp4 and they will be silently dropped by ffmpeg
@@ -245,7 +245,7 @@ class Downloader:
suffix = media_item.path.suffix + parse_url(m3u8.segments[0].absolute_uri).suffix
output = media_item.path.with_suffix(suffix)
- if await asyncio.to_thread(output.is_file):
+ if await aio.is_file(output):
return output
tasks_results = await self._download_segments(media_item, m3u8, download_folder)
@@ -281,7 +281,7 @@ class Downloader:
audio = await download(m3u8_group.audio)
video = await download(m3u8_group.video)
try:
- await asyncio.to_thread(temp_dir.rmdir)
+ await aio.rmdir(temp_dir)
except OSError:
pass
return video, audio, subtitles
@@ -321,7 +321,7 @@ class Downloader:
async def finalize_download(self, media_item: MediaItem, downloaded: bool) -> None:
if downloaded:
- await asyncio.to_thread(Path.chmod, media_item.path, 0o666)
+ await aio.chmod(media_item.path, 0o666)
await self.set_file_datetime(media_item, media_item.path)
self.attempt_task_removal(media_item)
self.manager.progress_manager.download_progress.add_completed()
@@ -454,7 +454,7 @@ class Downloader:
await self.check_file_can_download(media_item)
downloaded = await self.client.download_file(self.domain, media_item)
if downloaded:
- await asyncio.to_thread(Path.chmod, media_item.path, 0o666)
+ await aio.chmod(media_item.path, 0o666)
if not media_item.is_segment:
await self.set_file_datetime(media_item, media_item.path)
self.manager.progress_manager.download_progress.add_completed()
diff --git a/cyberdrop_dl/downloader/mega_nz.py b/cyberdrop_dl/downloader/mega_nz.py
index ea3d398d8..39d4bcae4 100644
--- a/cyberdrop_dl/downloader/mega_nz.py
+++ b/cyberdrop_dl/downloader/mega_nz.py
@@ -1,18 +1,16 @@
from __future__ import annotations
import asyncio
-from typing import TYPE_CHECKING, Any
+from typing import TYPE_CHECKING
import aiofiles
from mega.chunker import MegaChunker, get_chunks
-from cyberdrop_dl import storage
+from cyberdrop_dl import aio, storage
from cyberdrop_dl.clients.download_client import DownloadClient
from cyberdrop_dl.downloader.downloader import Downloader
if TYPE_CHECKING:
- from collections.abc import Coroutine
-
import aiohttp
from mega.data_structures import Crypto
from yarl import URL
@@ -54,13 +52,11 @@ class MegaDownloadClient(DownloadClient):
await self._post_download_check(media_item)
chunk_decryptor.check_integrity()
- def _pre_download_check(self, media_item: MediaItem) -> Coroutine[Any, Any, None]:
- def prepare() -> None:
- media_item.partial_file.parent.mkdir(parents=True, exist_ok=True)
- media_item.partial_file.unlink(missing_ok=True) # We can't resume
- media_item.partial_file.touch()
-
- return asyncio.to_thread(prepare)
+ @aio.to_thread
+ def _pre_download_check(self, media_item: MediaItem) -> None:
+ media_item.partial_file.parent.mkdir(parents=True, exist_ok=True)
+ media_item.partial_file.unlink(missing_ok=True) # We can't resume
+ media_item.partial_file.touch()
class MegaDownloader(Downloader):
diff --git a/cyberdrop_dl/scraper/scrape_mapper.py b/cyberdrop_dl/scraper/scrape_mapper.py
index 4e880f7a2..8e8d4d506 100644
--- a/cyberdrop_dl/scraper/scrape_mapper.py
+++ b/cyberdrop_dl/scraper/scrape_mapper.py
@@ -1,6 +1,5 @@
from __future__ import annotations
-import asyncio
import contextlib
import datetime
import logging
@@ -11,6 +10,7 @@ from typing import TYPE_CHECKING, Literal, Self, TypeVar
import aiofiles
from yarl import URL
+from cyberdrop_dl import aio
from cyberdrop_dl.clients.jdownloader import JDownloader
from cyberdrop_dl.constants import REGEX_LINKS, BlockedDomains
from cyberdrop_dl.crawlers import create_crawlers
@@ -157,7 +157,7 @@ class ScrapeMapper:
async def parse_input_file_groups(self) -> AsyncGenerator[tuple[str, list[AbsoluteHttpURL]]]:
"""Split URLs from input file by their groups."""
input_file = self.manager.config.files.input_file
- if not await asyncio.to_thread(input_file.is_file):
+ if not await aio.is_file(input_file):
yield ("", [])
return
diff --git a/cyberdrop_dl/utils/sorting.py b/cyberdrop_dl/utils/sorting.py
index 663fe2e78..6c53ba9dd 100644
--- a/cyberdrop_dl/utils/sorting.py
+++ b/cyberdrop_dl/utils/sorting.py
@@ -12,7 +12,7 @@ from typing import TYPE_CHECKING, Self
import imagesize
-from cyberdrop_dl import ffmpeg
+from cyberdrop_dl import aio, ffmpeg
from cyberdrop_dl.constants import FileExt, TempExt
from cyberdrop_dl.progress.sorting import SortingUI
from cyberdrop_dl.utils import strings
@@ -55,12 +55,12 @@ class Sorter:
)
async def run(self, *, disable_tui: bool = False) -> None:
- if not await asyncio.to_thread(self.input_dir.is_dir):
+ if not await aio.is_dir(self.input_dir):
logger.error(f"Sort directory '{self.input_dir}' does not exist", extra={"color": "red"})
return
logger.info("Sorting downloads...", extra={"color": "cyan"})
- await asyncio.to_thread(self.output_dir.mkdir, parents=True, exist_ok=True)
+ await aio.mkdir(self.output_dir, parents=True, exist_ok=True)
self.tui.disabled = disable_tui
with self.tui():
@@ -69,14 +69,16 @@ class Sorter:
async def _run(self) -> None:
async with asyncio.TaskGroup() as tg:
- async def _sort_folder(folder: Path) -> None:
- for path in await asyncio.to_thread(lambda: folder.glob("*")):
- if await asyncio.to_thread(path.is_file):
+ async def sort_subfolder(folder: Path) -> None:
+ async for path in aio.rglob(folder, "*"):
+ if await aio.is_file(path):
_ = tg.create_task(self._sort_file(folder.name, path))
- else:
- _ = tg.create_task(_sort_folder(path))
- await _sort_folder(self.input_dir)
+ async for path in aio.glob(self.input_dir, "*"):
+ if await aio.is_file(path):
+ _ = tg.create_task(self._sort_file(self.input_dir.name, path))
+ else:
+ _ = tg.create_task(sort_subfolder(path))
logger.info("DONE!", extra={"color": "green"})
_ = delete_empty_files_and_folders(self.input_dir)
@@ -192,7 +194,7 @@ class Sorter:
file,
base_name,
format_str,
- mtime=(await asyncio.to_thread(file.stat)).st_mtime,
+ mtime=(await aio.stat(file)).st_mtime,
sort_dir=self.output_dir,
**kwargs,
)
diff --git a/tests/test_storage.py b/tests/test_storage.py
index a0dd2e8b2..24ab55c78 100644
--- a/tests/test_storage.py
+++ b/tests/test_storage.py
@@ -1,6 +1,5 @@
from __future__ import annotations
-import asyncio
import dataclasses
import os
from pathlib import Path
@@ -8,7 +7,7 @@ from unittest import mock
import pytest
-from cyberdrop_dl import storage
+from cyberdrop_dl import aio, storage
def create_partition(path: str):
@@ -20,7 +19,7 @@ def find_partition(path: str):
async def test_unsupported_fs_should_not_return_zero() -> None:
- cwd = await asyncio.to_thread(Path().resolve)
+ cwd = await aio.resolve(Path())
free_space = await storage.get_free_space(cwd)
assert free_space > 0
with mock.patch("psutil.disk_usage", side_effect=OSError(None, "operation not supported")):
@@ -33,7 +32,7 @@ async def test_unsupported_fs_should_not_return_zero() -> None:
async def test_fuse_filesystem_should_not_return_zero() -> None:
- cwd = await asyncio.to_thread(Path().resolve)
+ cwd = await aio.resolve(Path())
partition = storage.find_partition(cwd)
assert partition
assert not storage.is_fuse_fs(cwd)