Bulk asynchronous downloader for multiple file hosts
Python asynciobunkrcyberdropdownloaderdropboxfilestergofilegoogle-drivemediafiremegamega-nzonedrivepatreonpawchivepinterestpixeldraintransfer-ittwitchtwittervk
refactor: rework storage module (#33)
NTFSvolumec8190bb66095
diff --git a/cyberdrop_dl/clients/download_client.py b/cyberdrop_dl/clients/download_client.pyindex a96a15f0d..3fa7f78ab 100644--- a/cyberdrop_dl/clients/download_client.py+++ b/cyberdrop_dl/clients/download_client.py@@ -10,7 +10,7 @@ from typing import TYPE_CHECKING, Anyimport aiofiles-from cyberdrop_dl import aio, constants+from cyberdrop_dl import aio, constants, storagefrom cyberdrop_dl.clients.response import AbstractResponsefrom cyberdrop_dl.constants import FILE_FORMATSfrom cyberdrop_dl.data_structures.url_objects import AbsoluteHttpURL@@ -234,7 +234,7 @@ class DownloadClient:"""Appends content to a file."""assert media_item.task_id is not None- check_free_space = self.make_free_space_checker(media_item)+ check_free_space = storage.create_free_space_checker(media_item)check_download_speed = self.make_speed_checker(media_item)await check_free_space()await self._pre_download_check(media_item)@@ -264,17 +264,6 @@ class DownloadClient:await aio.unlink(media_item.partial_file, missing_ok=True)raise DownloadError(HTTPStatus.INTERNAL_SERVER_ERROR, message="File is empty")- def make_free_space_checker(self, media_item: MediaItem) -> Callable[[], Coroutine[Any, Any, None]]:- current_chunk = 0-- async def check_free_space() -> None:- nonlocal current_chunk- if current_chunk % _FREE_SPACE_CHECK_PERIOD == 0:- await self.manager.storage_manager.check_free_space(media_item)- current_chunk += 1-- return check_free_space-def make_speed_checker(self, media_item: MediaItem) -> Callable[[], None]:last_slow_speed_read = Nonediff --git a/cyberdrop_dl/director.py b/cyberdrop_dl/director.pyindex b07a7b136..dab7167ac 100644--- a/cyberdrop_dl/director.py+++ b/cyberdrop_dl/director.py@@ -12,7 +12,7 @@ from typing import TYPE_CHECKING, ParamSpec, TypeVarfrom pydantic import ValidationError-from cyberdrop_dl import constants, env+from cyberdrop_dl import aio, constants, env, storagefrom cyberdrop_dl.dependencies import browser_cookie3from cyberdrop_dl.managers.manager import Managerfrom cyberdrop_dl.scraper.scrape_mapper import ScrapeMapper@@ -213,13 +213,6 @@ def _setup_manager(args: Sequence[str] | None = None) -> Manager:return manager-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--class Director:"""Creates a manager and runs it"""@@ -231,15 +224,15 @@ class Director:async def async_run(self) -> None:try:- await _run_manager(self.manager)+ async with storage.monitor(self.manager.global_config.general.required_free_space):+ await _run_manager(self.manager)finally:await self.manager.close()def _run(self) -> int:exit_code = _C.ERRORwith contextlib.suppress(Exception):- with asyncio.Runner(loop_factory=_loop_factory) as runner:- runner.run(self.async_run())+ aio.run(self.async_run())exit_code = _C.OKreturn exit_codediff --git a/cyberdrop_dl/downloader/downloader.py b/cyberdrop_dl/downloader/downloader.pyindex 75620b80c..6fe2adc2e 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 aio, constants, ffmpeg+from cyberdrop_dl import aio, constants, ffmpeg, storagefrom cyberdrop_dl.data_structures.url_objects import HlsSegment, MediaItemfrom cyberdrop_dl.exceptions import (DownloadError,@@ -330,7 +330,7 @@ class Downloader:async def check_file_can_download(self, media_item: MediaItem) -> None:"""Checks if the file can be downloaded."""- await self.manager.storage_manager.check_free_space(media_item)+ await storage.check(media_item)if not self.manager.client_manager.check_allowed_filetype(media_item):raise RestrictedFiletypeError(origin=media_item)if not await self.manager.client_manager.check_file_duration(media_item):diff --git a/cyberdrop_dl/downloader/mega_nz.py b/cyberdrop_dl/downloader/mega_nz.pyindex 73f47b330..828a4571c 100644--- a/cyberdrop_dl/downloader/mega_nz.py+++ b/cyberdrop_dl/downloader/mega_nz.py@@ -6,6 +6,7 @@ from typing import TYPE_CHECKING, Anyimport aiofilesfrom mega.chunker import MegaChunker, get_chunks+from cyberdrop_dl import storagefrom cyberdrop_dl.clients.download_client import DownloadClientfrom cyberdrop_dl.downloader.downloader import Downloader@@ -30,7 +31,7 @@ class MegaDownloadClient(DownloadClient):"""Appends content to a file."""assert media_item.task_id is not None- check_free_space = self.make_free_space_checker(media_item)+ check_free_space = storage.create_free_space_checker(media_item)check_download_speed = self.make_speed_checker(media_item)await check_free_space()await self._pre_download_check(media_item)diff --git a/cyberdrop_dl/managers/manager.py b/cyberdrop_dl/managers/manager.pyindex 918d159f8..c82ff0b8c 100644--- a/cyberdrop_dl/managers/manager.py+++ b/cyberdrop_dl/managers/manager.py@@ -20,7 +20,6 @@ from cyberdrop_dl.managers.live_manager import LiveManagerfrom cyberdrop_dl.managers.log_manager import LogManagerfrom cyberdrop_dl.managers.path_manager import PathManagerfrom cyberdrop_dl.managers.progress_manager import ProgressManager-from cyberdrop_dl.managers.storage_manager import StorageManagerfrom cyberdrop_dl.utils.logger import LogHandler, QueuedLogger, logfrom cyberdrop_dl.utils.utilities import close_if_defined, get_system_information@@ -50,7 +49,6 @@ class Manager:self.log_manager: LogManager = field(init=False)self.db_manager: Database = field(init=False)self.client_manager: ClientManager = field(init=False)- self.storage_manager: StorageManager = field(init=False)self.progress_manager: ProgressManager = field(init=False)self.live_manager: LiveManager = field(init=False)@@ -108,11 +106,6 @@ class Manager:if not isinstance(self.client_manager, ClientManager):self.client_manager = ClientManager(self)await self.client_manager.startup()- if not isinstance(self.storage_manager, StorageManager):- self.storage_manager = StorageManager(self)-- elif self.states.RUNNING.is_set():- await self.storage_manager.reset()await self.async_db_hash_startup()@@ -202,7 +195,6 @@ class Manager:await self.async_db_close()self.client_manager = await close_if_defined(self.client_manager)- self.storage_manager = await close_if_defined(self.storage_manager)self.cache_manager = await close_if_defined(self.cache_manager)while self.loggers:diff --git a/cyberdrop_dl/managers/progress_manager.py b/cyberdrop_dl/managers/progress_manager.pyindex 8f6b46454..df99171a6 100644--- a/cyberdrop_dl/managers/progress_manager.py+++ b/cyberdrop_dl/managers/progress_manager.py@@ -141,7 +141,7 @@ class ProgressManager:returnend_time = time.perf_counter()runtime = timedelta(seconds=int(end_time - start_time))- total_data_written = ByteSize(self.manager.storage_manager.total_data_written).human_readable(decimal=True)+ total_data_written = ByteSize(self.file_progress.total_data_written).human_readable(decimal=True)log_spacer(20)log("Printing Stats...\n", 20)diff --git a/cyberdrop_dl/managers/storage_manager.py b/cyberdrop_dl/managers/storage_manager.pydeleted file mode 100644index 670b17e13..000000000--- a/cyberdrop_dl/managers/storage_manager.py+++ /dev/null@@ -1,254 +0,0 @@-from __future__ import annotations--import asyncio-import functools-import itertools-from collections import defaultdict-from dataclasses import asdict, dataclass, field-from pathlib import Path-from typing import TYPE_CHECKING, Final, NamedTuple--import psutil-from pydantic import ByteSize--from cyberdrop_dl.exceptions import InsufficientFreeSpaceError-from cyberdrop_dl.utils.logger import log, log_debug--if TYPE_CHECKING:- from collections.abc import Generator-- from psutil._ntuples import sdiskpart-- from cyberdrop_dl.data_structures.url_objects import MediaItem- from cyberdrop_dl.managers.manager import Manager---@dataclass(frozen=True, slots=True, order=True)-class DiskPartition:- mountpoint: Path- device: Path = field(compare=False)- fstype: str = field(compare=False)- opts: str = field(compare=False)-- @staticmethod- def from_psutil(diskpart: sdiskpart) -> DiskPartition:- # Resolve converts any mapped drive to UNC paths (windows)- return DiskPartition(- Path(diskpart.mountpoint).resolve(),- Path(diskpart.device).resolve(),- diskpart.fstype,- diskpart.opts,- )---class MountStats(NamedTuple):- partition: DiskPartition- free_space: ByteSize-- def __str__(self) -> str:- free_space = self.free_space.human_readable(decimal=True)- stats_as_dict = asdict(self.partition) | {"free_space": free_space}- return ", ".join(f"'{k}': '{v}'" for k, v in stats_as_dict.items())---_CHECK_PERIOD: Final = 2 # how often the check_free_space_loop will run (in seconds)-_LOG_PERIOD: Final = 10 # log storage details every <x> loops, AKA log every 20 (2x10) seconds,---class StorageManager:- """Runs an infinite loop to keep an updated value of the available space on all storage devices."""-- def __init__(self, manager: Manager):- self.manager: Manager = manager- self.total_data_written: int = 0- self._used_mounts: set[Path] = set()- self._free_space: dict[Path, int] = {}- self._mount_addition_locks: dict[Path, asyncio.Lock] = defaultdict(asyncio.Lock)- self._updated: asyncio.Event = asyncio.Event()- self._partitions = list(_get_disk_partitions())- self._loop = asyncio.create_task(self._check_free_space_loop())- self._unavailable_mounts: set[Path] = set()-- @property- def mounts(self) -> tuple[Path, ...]:- return tuple(p.mountpoint for p in self._partitions)-- @property- def _simplified_stats(self) -> str:- stats_as_str = "\n".join(f" {mount_stats!s}" for mount_stats in self._mount_stats())- return f"Storage status:\n {stats_as_str}"-- def _mount_stats(self) -> Generator[MountStats]:- """Returns information of every used mount + its free space."""-- for partition in self._partitions:- free_space = self._free_space.get(partition.mountpoint)- if free_space is not None:- yield MountStats(partition, ByteSize(free_space))-- async def check_free_space(self, media_item: MediaItem) -> None:- """Checks if there is enough free space to download this item."""-- await self.manager.states.RUNNING.wait()- if not await self._has_sufficient_space(media_item.download_folder):- raise InsufficientFreeSpaceError(origin=media_item)-- async def reset(self) -> None:- # This is causing lockups- # await self._updated.wait() # Make sure a query is not running right now- self.total_data_written = 0- self._used_mounts = set()- self._free_space = {}-- async def close(self) -> None:- await self.reset()- try:- self._loop.cancel()- await self._loop- except asyncio.CancelledError:- pass-- async def _check_nt_network_drive(self, folder: Path) -> None:- """Checks is the drive of this folder is a Windows network drive (UNC or unknown mapped drive) and exists."""- # See: https://github.com/jbsparrow/CyberDropDownloader/issues/860- if not psutil.WINDOWS:- return-- # We can discard mapped drives because they would have been converted to UNC path at startup- # calling resolve on a mapped network drive returns its UNC path- # it would only still be a mapped drive is the network address is not available- is_mapped_drive = ":" in folder.drive and len(folder.drive) == 2- is_unc_path = folder.drive.startswith("\\\\")- if is_mapped_drive or not is_unc_path:- return-- folder_drive = _drive_as_path(folder.drive)- async with self._mount_addition_locks[folder_drive]:- if folder_drive in itertools.chain(self._unavailable_mounts, self.mounts):- return-- msg = f"Checking new possible network_drive: '{folder_drive}' for folder '{folder}'"- log_debug(msg)-- try:- is_dir = await asyncio.to_thread(folder_drive.is_dir)- except OSError:- is_dir = False-- if is_dir:- net_drive = DiskPartition(folder_drive, folder_drive, "network_drive", "")- self._partitions.append(net_drive)-- else:- self._unavailable_mounts.add(folder_drive)-- async def _has_sufficient_space(self, folder: Path) -> bool:- """Checks if there is enough free space to download to this folder.-- `folder` must be an absolute path"""-- await self._check_nt_network_drive(folder)- mount = _get_mount_point(folder, self.mounts)- if not mount:- return False-- async with self._mount_addition_locks[mount]:- if mount not in self._free_space:- # Manually query this mount now. Next time it will be part of the loop-- self._free_space[mount] = await self._get_free_space(mount)- self._used_mounts.add(mount)- log(f"A new mountpoint ('{mount!s}') will be used for '{folder}'")- log(self._simplified_stats)-- free_space = self._free_space[mount]- if free_space == -1:- return True- return free_space > self.manager.global_config.general.required_free_space-- async def _get_free_space(self, mount: Path) -> int:- exc_info = None- free_space = 0-- try:- result = await asyncio.to_thread(psutil.disk_usage, str(mount))- free_space = result.free- except OSError as e:- if "operation not supported" in str(e).casefold():- exc_info = e- else:- raise-- if exc_info or (free_space == 0 and self._is_fuse_fs(mount)):- msg = f"Unable to get free space from mount point ('{mount!s}')'. Skipping free space check"- log(msg, 40, exc_info=exc_info)- free_space = -1-- return free_space-- def _get_partition(self, mount: Path) -> DiskPartition | None:- for partition in self._partitions:- if mount.is_relative_to(partition.mountpoint):- return partition-- def _is_fuse_fs(self, mount: Path) -> bool:- if partition := self._get_partition(mount):- return "fuse" in partition.fstype- return False-- async def _check_free_space_loop(self) -> None:- """Infinite loop to get free space of all used mounts and update internal dict"""-- last_check = -1- while True:- await self.manager.states.RUNNING.wait()- self._updated.clear()- last_check += 1- if self._used_mounts:- used_mounts = sorted(mount for mount in self._used_mounts if self._free_space[mount] != -1)- tasks = [self._get_free_space(mount) for mount in used_mounts]- results = await asyncio.gather(*tasks)- for mount, free_space in zip(used_mounts, results, strict=True):- self._free_space[mount] = free_space- if last_check % _LOG_PERIOD == 0:- log_debug(self._simplified_stats)-- self._updated.set()- await asyncio.sleep(_CHECK_PERIOD)--[email protected]_cache-def _get_mount_point(folder: Path, all_mounts: tuple[Path, ...]) -> Path | None:- # Cached for performance.- # It's not an expensive operation nor IO blocking, but it's very common for multiple files to share the same download folder- # ex: HLS downloads could have over a thousand segments. All of them will go to the same folder- assert folder.is_absolute()- possible_mountpoints = (mount for mount in all_mounts if folder.is_relative_to(mount))-- # Get the closest mountpoint to `folder`- # mount_a = /home/user/ -> points to an internal SSD- # mount_b = /home/user/USB -> points to an external USB drive- # If `folder`` is `/home/user/USB/videos`, the correct mountpoint is mount_b- if mount_point := max(possible_mountpoints, key=lambda path: len(path.parts), default=None):- return mount_point-- # Mount point for this path does not exists- # This will only happen on Windows, ex: an USB drive (`D:`) that is not currently available (AKA disconnected)- # On Unix there's always at least 1 mountpoint, root (`/`)- msg = f"No available mountpoint found for '{folder}'"- msg += f"\n -> drive = '{_drive_as_path(folder.drive)}' , last_parent = '{folder.parents[-1]}'"- log(msg, 40)---def _drive_as_path(drive: str) -> Path:- is_mapped_drive = ":" in drive and len(drive) == 2- return Path(f"{drive}/" if is_mapped_drive else drive)---def _get_disk_partitions() -> Generator[DiskPartition]:- for p in psutil.disk_partitions(all=True):- try:- yield DiskPartition.from_psutil(p)- except OSError as e:- msg = f"Unable to get information about {p.mountpoint}. All files with that mountpoint as target will be skipped: {e!r}"- log(msg, 40)diff --git a/cyberdrop_dl/storage.py b/cyberdrop_dl/storage.pynew file mode 100644index 000000000..eb2ec9b5b--- /dev/null+++ b/cyberdrop_dl/storage.py@@ -0,0 +1,282 @@+"""Runs an infinite loop to keep an updated value of the available space on all storage devices."""++from __future__ import annotations++import asyncio+import contextlib+import dataclasses+import functools+import logging+from collections import defaultdict+from contextvars import ContextVar+from pathlib import Path+from typing import TYPE_CHECKING, Final++import psutil+from pydantic import ByteSize++from cyberdrop_dl.exceptions import InsufficientFreeSpaceError++if TYPE_CHECKING:+ from collections.abc import AsyncGenerator, Awaitable, Callable, Generator++ from cyberdrop_dl.data_structures import MediaItem+++logger = logging.getLogger(__name__)+_required_free_space: ContextVar[int] = ContextVar("_required_free_space")+_PARTITIONS: list[DiskPartition] = []+_UNAVAILABLE: set[Path] = set()+_LOCKS: dict[Path, asyncio.Lock] = defaultdict(asyncio.Lock)+_CHECK_PERIOD: Final = 2 # how often the check_free_space_loop will run (in seconds)+_LOG_PERIOD: Final = 10 # log storage details every <x> loops, AKA log every 20 (2x10) seconds,+_free_space: dict[Path, int] = {}+_running = asyncio.Event()++[email protected](frozen=True, slots=True, order=True)+class DiskPartition:+ mountpoint: Path+ device: Path = dataclasses.field(compare=False)+ fstype: str = dataclasses.field(compare=False)+ opts: str = dataclasses.field(compare=False)++[email protected](frozen=True, slots=True, order=True)+class DiskPartitionStats:+ partition: DiskPartition+ free_space: ByteSize++ def __str__(self) -> str:+ free_space = self.free_space.human_readable(decimal=True)+ stats = dataclasses.asdict(self.partition) | {"free_space": free_space}+ return ", ".join(f"'{k}': '{v}'" for k, v in stats.items())+++class _Stats:+ def __str__(self) -> str:+ info = "\n".join(f" {stats!s}" for stats in partition_stats())+ return f"Storage status:\n {info}"+++async def get_free_space(path: Path) -> int:+ unsupported = None+ free_space = 0++ try:+ usage = await asyncio.to_thread(psutil.disk_usage, str(path))+ free_space = usage.free+ except OSError as e:+ if "operation not supported" not in str(e).casefold():+ raise++ unsupported = e++ if unsupported or (free_space == 0 and is_fuse_fs(path)):+ logger.error(+ f"Unable to get free space from mount point ('{path}')'. Skipping free space check",+ exc_info=unsupported,+ )+ return -1++ return free_space+++async def has_sufficient_space(folder: Path) -> bool:+ await _check_nt_network_drive(folder)+ mount = _get_mount_point(folder)+ if not mount:+ return False++ free_space = _free_space.get(mount)+ if free_space is None:+ async with _LOCKS[mount]:+ free_space = _free_space.get(mount)+ if free_space is None:+ # Manually query this mount now. Next time it will be part of the loop++ free_space = _free_space[mount] = await get_free_space(mount)+ logger.info(f"A new mountpoint ('{mount!s}') will be used for '{folder}'")+ logger.info(_Stats())++ return free_space == -1 or free_space > _required_free_space.get()+++async def check(media_item: MediaItem) -> None:+ """Checks if there is enough free space to download this item."""++ if not await has_sufficient_space(media_item.download_folder):+ raise InsufficientFreeSpaceError(media_item)+++def find_partition(path: Path) -> DiskPartition | None:+ if not path.is_absolute():+ raise ValueError(f"{path!r} is not absolute")++ possible_partitions = (p for p in partitions() if path.is_relative_to(p.mountpoint))++ # Get the closest mountpoint to `folder`+ # mount_a = /home/user/ -> points to an internal SSD+ # mount_b = /home/user/USB -> points to an external USB drive+ # If `folder`` is `/home/user/USB/videos`, the correct mountpoint is mount_b+ if partition := max(possible_partitions, key=lambda p: len(p.mountpoint.parts), default=None):+ return partition+++def is_fuse_fs(path: Path) -> bool:+ if partition := find_partition(path):+ return "fuse" in partition.fstype+ return False+++def create_free_space_checker(media_item: MediaItem, *, frecuency: int = 5) -> Callable[[], Awaitable[None]]:+ current_chunk = 0++ async def checker() -> None:+ nonlocal current_chunk+ if current_chunk % frecuency == 0:+ await check(media_item)+ current_chunk += 1++ return checker+++def partitions() -> tuple[DiskPartition, ...]:+ if not _PARTITIONS:+ _PARTITIONS.extend(_get_disk_partitions())+ return tuple(_PARTITIONS)+++def partition_stats() -> Generator[DiskPartitionStats]:+ for partition in partitions():+ free_space = _free_space.get(partition.mountpoint)+ if free_space is not None:+ yield DiskPartitionStats(partition, ByteSize(free_space))+++def clear_cache() -> None:+ _PARTITIONS.clear()+ _UNAVAILABLE.clear()+ _LOCKS.clear()+ _free_space.clear()+ _get_mount_point.cache_clear()+++async def _start_loop() -> None:+ """Infinite loop to get free space of all used mounts and update internal dict"""++ async def update():+ mountpoints = sorted(mount for mount, free_space in _free_space.items() if free_space != -1)+ if not mountpoints:+ return++ results = await asyncio.gather(*map(get_free_space, mountpoints))+ _free_space.update(zip(mountpoints, results, strict=True))++ last_check = -1+ while True:+ if _free_space:+ last_check += 1+ await update()++ if last_check % _LOG_PERIOD == 0:+ logger.debug(_Stats())++ await asyncio.sleep(_CHECK_PERIOD)++[email protected]_cache+def _get_mount_point(folder: Path) -> Path | None:+ # Cached for performance.+ # It's not an expensive operation nor IO blocking, but it's very common for multiple files to share the same download folder+ # ex: HLS downloads could have over a thousand segments. All of them will go to the same folder+ if partition := find_partition(folder):+ return partition.mountpoint++ # Mount point for this path does not exists+ # This will only happen on Windows, ex: an USB drive (`D:`) that is not currently available (AKA disconnected)+ # On Unix there's always at least 1 mountpoint, root (`/`)+ msg = f"No available mountpoint found for '{folder}'"+ msg += f"\n -> drive = '{_drive_as_path(folder.drive)}' , last_parent = '{folder.parents[-1]}'"+ logger.error(msg)+++def _drive_as_path(drive: str) -> Path:+ is_mapped_drive = ":" in drive and len(drive) == 2+ return Path(f"{drive}/" if is_mapped_drive else drive)+++def _get_disk_partitions() -> Generator[DiskPartition]:+ for diskpart in psutil.disk_partitions(all=True):+ try:+ # Resolve converts any mapped drive to UNC paths (windows)+ yield DiskPartition(+ Path(diskpart.mountpoint).resolve(),+ Path(diskpart.device).resolve(),+ diskpart.fstype,+ diskpart.opts,+ )+ except OSError as e:+ logger.error(+ f"Unable to get information about {diskpart.mountpoint}. All files with that mountpoint as target will be skipped: {e!r}"+ )+++async def _check_nt_network_drive(folder: Path) -> None:+ """Checks is the drive of this folder is a Windows network drive (UNC or unknown mapped drive) and exists.++ See: https://github.com/jbsparrow/CyberDropMediaItemer/issues/860+ """+ if not psutil.WINDOWS:+ return++ # We can discard mapped drives because they would have been converted to UNC path at startup+ # calling resolve on a mapped network drive returns its UNC path+ # it would only still be a mapped drive is the network address is not available+ is_mapped_drive = ":" in folder.drive and len(folder.drive) == 2+ is_unc_path = folder.drive.startswith("\\\\")+ if is_mapped_drive or not is_unc_path:+ return++ folder_drive = _drive_as_path(folder.drive)++ if folder_drive in _UNAVAILABLE:+ return++ mounts = tuple(p.mountpoint for p in partitions())+ if folder_drive in mounts:+ return++ async with _LOCKS[folder_drive]:+ if folder_drive in _UNAVAILABLE or folder_drive in mounts:+ return++ logger.debug(f"Checking new possible network_drive: '{folder_drive}' for folder '{folder}'")++ try:+ is_dir = await asyncio.to_thread(folder_drive.is_dir)+ except OSError:+ is_dir = False++ if is_dir:+ _PARTITIONS.append(DiskPartition(folder_drive, folder_drive, "network_drive", ""))+ _get_mount_point.cache_clear()++ else:+ _UNAVAILABLE.add(folder_drive)+++async def monitor(required_free_space: int) -> AsyncGenerator[None]:+ loop = asyncio.create_task(_start_loop(), name="storage monitor")+ token = _required_free_space.set(required_free_space)+ await asyncio.sleep(0)+ try:+ yield+ finally:+ _required_free_space.reset(token)+ try:+ _ = loop.cancel("On monitor exit")+ await loop+ except asyncio.CancelledError:+ passdiff --git a/cyberdrop_dl/ui/progress/file_progress.py b/cyberdrop_dl/ui/progress/file_progress.pyindex d2b17ed3e..0e8fa5894 100644--- a/cyberdrop_dl/ui/progress/file_progress.py+++ b/cyberdrop_dl/ui/progress/file_progress.py@@ -41,6 +41,7 @@ class FileProgress(DequeProgress):if manager.parsed_args.cli_only_args.portrait:use_columns = vertical_columnsself._progress = Progress(*use_columns)+ self.total_data_written = 0super().__init__("Downloads", visible_tasks_limit)def get_queue_length(self) -> int:@@ -66,7 +67,7 @@ class FileProgress(DequeProgress):def advance_file(self, task_id: TaskID, amount: int) -> None:"""Advances the progress of the given task by the given amount."""- self.manager.storage_manager.total_data_written += amount+ self.total_data_written += amountself._progress.advance(task_id, amount)def get_speed(self, task_id: TaskID) -> float:diff --git a/tests/test_storage.py b/tests/test_storage.pyindex 0e6badec1..a0dd2e8b2 100644--- a/tests/test_storage.py+++ b/tests/test_storage.py@@ -1,45 +1,87 @@+from __future__ import annotations+import asyncioimport dataclasses-from collections.abc import AsyncGenerator+import osfrom pathlib import Pathfrom unittest import mockimport pytest-from cyberdrop_dl.managers.manager import Manager-from cyberdrop_dl.managers.storage_manager import StorageManager+from cyberdrop_dl import storage++def create_partition(path: str):+ return storage.DiskPartition(Path(path), Path(path), "", "")-async def storage(running_manager: Manager) -> AsyncGenerator[StorageManager]:- yield StorageManager(running_manager)+def find_partition(path: str):+ return storage.find_partition(Path(path))-async def test_unsupported_fs_should_not_return_zero(storage: StorageManager) -> None:++async def test_unsupported_fs_should_not_return_zero() -> None:cwd = await asyncio.to_thread(Path().resolve)- free_space = await storage._get_free_space(cwd)+ free_space = await storage.get_free_space(cwd)assert free_space > 0with mock.patch("psutil.disk_usage", side_effect=OSError(None, "operation not supported")):- free_space = await storage._get_free_space(cwd)+ free_space = await storage.get_free_space(cwd)assert free_space == -1with mock.patch("psutil.disk_usage", side_effect=OSError(None, "another error")):with pytest.raises(OSError):- await storage._get_free_space(cwd)+ _ = await storage.get_free_space(cwd)-async def test_fuse_filesystem_should_not_return_zero(storage: StorageManager) -> None:+async def test_fuse_filesystem_should_not_return_zero() -> None:cwd = await asyncio.to_thread(Path().resolve)- partition = storage._get_partition(cwd)+ partition = storage.find_partition(cwd)assert partition- storage._partitions = [dataclasses.replace(partition, fstype="fuse")]+ assert not storage.is_fuse_fs(cwd)+ storage._PARTITIONS = [dataclasses.replace(partition, fstype="fuse")] # pyright: ignore[reportPrivateUsage]+ assert storage.is_fuse_fs(cwd)- free_space = await storage._get_free_space(cwd)+ free_space = await storage.get_free_space(cwd)assert free_space > 0class NullUsage:free = 0with mock.patch("psutil.disk_usage", return_value=NullUsage()):- free_space = await storage._get_free_space(cwd)+ free_space = await storage.get_free_space(cwd)assert free_space == -1+++def test_storage_only_work_with_abs_paths() -> None:+ cwd = Path()+ with pytest.raises(ValueError):+ _ = storage.find_partition(cwd)++ assert storage.find_partition(cwd.resolve())++[email protected](os.name == "nt", reason="Test paths are only posix")+async def test_find_partition_finds_the_correct_partition() -> None:++ root, home, usb, external_ssd = partitions = [+ create_partition(path) for path in ("/", "/home", "/mnt/USB", "/home/external_SSD")+ ]++ storage._PARTITIONS = partitions # pyright: ignore[reportPrivateUsage]++ assert find_partition("/swap_file") is root+ assert find_partition("/home/user/.bash_rc") is home+ assert find_partition("/home/external_SSD/song.mp3") is external_ssd+ assert find_partition("/mnt/USB") is usb+ assert find_partition("/mnt") is root++[email protected](os.name != "nt", reason="Test paths are only for windows")+async def test_find_partition_finds_the_correct_partition_windows() -> None:+ c_drive, d_drive = partitions = [create_partition(path) for path in ("C:/", "D:/")]++ storage._PARTITIONS = partitions # pyright: ignore[reportPrivateUsage]++ assert find_partition("C:/pagefile") is c_drive+ assert find_partition("C:/") is c_drive+ assert find_partition("D:/music/song.mp3") is d_drive+ assert find_partition("Z:/") is None