Skip to content

Bulk asynchronous downloader for multiple file hosts

refactor: make `create_task_id` a context manager (#1146)

NTFSvolume7ddded6d42ce
diff --git a/cyberdrop_dl/clients/hash_client.py b/cyberdrop_dl/clients/hash_client.py
index 1974fd474..7988605bb 100644
--- a/cyberdrop_dl/clients/hash_client.py
+++ b/cyberdrop_dl/clients/hash_client.py
@@ -69,6 +69,7 @@ class HashClient:
return
await self.manager.states.RUNNING.wait()
try:
+ assert media_item.original_filename
hash = await self.update_db_and_retrive_hash(
media_item.complete_file, media_item.original_filename, media_item.referer
)
@@ -78,7 +79,7 @@ class HashClient:
async def update_db_and_retrive_hash(
self, file: Path | str, original_filename: str | None = None, referer: URL | None = None
- ):
+ ) -> str | None:
file = Path(file)
if file.suffix == ".part":
return
@@ -94,10 +95,10 @@ class HashClient:
async def _update_db_and_retrive_hash_helper(
self,
file: Path | str,
- original_filename: str | None = None,
- referer: URL | None = None,
- hash_type: str | None = None,
- ) -> str:
+ original_filename: str | None,
+ referer: URL | None,
+ hash_type: str,
+ ) -> str | None:
"""Generates hash of a file."""
self.manager.progress_manager.hash_progress.update_currently_hashing(file)
hash = await self.manager.db_manager.hash_table.get_file_hash_exists(file, hash_type)
@@ -123,9 +124,12 @@ class HashClient:
)
except Exception as e:
log(f"Error hashing {file} : {e}", 40, exc_info=True)
- return hash
+ else:
+ return hash
- async def save_hash_data(self, media_item: MediaItem, hash: str):
+ 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.complete_file.resolve)
size = await asyncio.to_thread(get_size_or_none, media_item.complete_file)
assert size
diff --git a/cyberdrop_dl/crawlers/crawler.py b/cyberdrop_dl/crawlers/crawler.py
index 49970b19a..2498d4071 100644
--- a/cyberdrop_dl/crawlers/crawler.py
+++ b/cyberdrop_dl/crawlers/crawler.py
@@ -1,14 +1,16 @@
from __future__ import annotations
import asyncio
+import contextlib
import datetime
+import inspect
import re
from abc import ABC, abstractmethod
from collections.abc import Iterable, Mapping
from dataclasses import dataclass, field
from functools import partial, wraps
from pathlib import Path
-from typing import TYPE_CHECKING, Any, ClassVar, NamedTuple, NoReturn, ParamSpec, TypeAlias, TypeVar, final
+from typing import TYPE_CHECKING, Any, ClassVar, Concatenate, NamedTuple, ParamSpec, TypeAlias, TypeVar, final
import yarl
from aiolimiter import AsyncLimiter
@@ -17,7 +19,7 @@ from yarl import URL
from cyberdrop_dl import constants
from cyberdrop_dl.data_structures.url_objects import AbsoluteHttpURL, MediaItem, ScrapeItem
from cyberdrop_dl.downloader.downloader import Downloader
-from cyberdrop_dl.exceptions import MaxChildrenError, NoExtensionError
+from cyberdrop_dl.exceptions import MaxChildrenError, NoExtensionError, ScrapeError
from cyberdrop_dl.scraper import filters
from cyberdrop_dl.utils import css, m3u8
from cyberdrop_dl.utils.database.tables.history_table import get_db_path
@@ -41,6 +43,7 @@ from cyberdrop_dl.utils.utilities import (
P = ParamSpec("P")
R = TypeVar("R")
T = TypeVar("T")
+_T_co = TypeVar("_T_co", covariant=True)
if TYPE_CHECKING:
@@ -48,6 +51,7 @@ if TYPE_CHECKING:
from aiohttp_client_cache.response import AnyResponse
from bs4 import BeautifulSoup, Tag
+ from rich.progress import TaskID
from cyberdrop_dl.clients.scraper_client import ScraperClient
from cyberdrop_dl.managers.manager import Manager
@@ -57,7 +61,7 @@ OneOrTuple: TypeAlias = T | tuple[T, ...]
SupportedPaths: TypeAlias = Mapping[str, OneOrTuple[str]]
SupportedDomains: TypeAlias = OneOrTuple[str]
-UNKNOWN_URL_PATH_MSG = "Unknown URL path"
+
HASH_PREFIXES = "md5:", "sha1:", "sha256:", "xxh128:"
VALID_RESOLUTION_NAMES = "4K", "8K", "HQ", "Unknown"
@@ -81,36 +85,6 @@ class CrawlerInfo(NamedTuple):
supported_paths: SupportedPaths
-def create_task_id(func: Callable[P, Coroutine[None, None, R]]) -> Callable[P, Coroutine[None, None, R | None]]:
- """Wrapper that handles `task_id` creation and removal for scrape items"""
-
- @wraps(func)
- async def wrapper(*args, **kwargs) -> R | None:
- self: Crawler = args[0]
- scrape_item: ScrapeItem = args[1]
- await self.manager.states.RUNNING.wait()
- task_id = self.scraping_progress.add_task(scrape_item.url)
- try:
- if not self.SKIP_PRE_CHECK:
- _pre_check_scrape_item(scrape_item)
- return await func(scrape_item, **kwargs) # type: ignore
- except ValueError:
- log(f"Scrape Failed: {UNKNOWN_URL_PATH_MSG}: {scrape_item.url}", 40)
- self.manager.progress_manager.scrape_stats_progress.add_failure(UNKNOWN_URL_PATH_MSG)
- await self.manager.log_manager.write_scrape_error_log(scrape_item.url, UNKNOWN_URL_PATH_MSG)
- except MaxChildrenError:
-
- @error_handling_wrapper
- async def raise_e(self, scrape_item: ScrapeItem) -> NoReturn:
- raise
-
- await raise_e(self, scrape_item)
- finally:
- self.scraping_progress.remove_task(task_id)
-
- return wrapper
-
-
class Crawler(ABC):
SUPPORTED_DOMAINS: ClassVar[SupportedDomains] = ()
SUPPORTED_PATHS: ClassVar[SupportedPaths] = {}
@@ -128,7 +102,6 @@ class Crawler(ABC):
def __init__(self, manager: Manager) -> None:
self.manager = manager
self.downloader: Downloader = field(init=False)
- self.scraping_progress = manager.progress_manager.scraping_progress
self.client: ScraperClient = field(init=False)
self.startup_lock = asyncio.Lock()
self.request_limiter = AsyncLimiter(10, 1)
@@ -142,6 +115,10 @@ class Crawler(ABC):
self._semaphore = asyncio.Semaphore(20)
self.__post_init__()
+ @final
+ def create_task(self, coro: Coroutine[Any, Any, _T_co]) -> asyncio.Task[_T_co]:
+ return self.manager.task_group.create_task(coro)
+
def __post_init__(self) -> None: ... # noqa: B027
def __init_subclass__(
@@ -207,29 +184,73 @@ class Crawler(ABC):
async def async_startup(self) -> None: ... # noqa: B027
@final
- async def run(self, item: ScrapeItem) -> None:
+ async def run(self, scrape_item: ScrapeItem) -> None:
"""Runs the crawler loop."""
- if not item.url.host:
+ if not scrape_item.url.host:
return
if self.disabled:
return
- await self.manager.states.RUNNING.wait()
self.waiting_items += 1
+ async with self._semaphore:
+ await self.manager.states.RUNNING.wait()
+ self.waiting_items -= 1
+ og_url = scrape_item.url
+ scrape_item.url = url = self.transform_url(scrape_item.url)
+ if og_url != url:
+ log(f"URL transformed: \n old: {og_url} \n new: {url}")
+
+ if url.path_qs in self.scraped_items:
+ return log(f"Skipping {url} as it has already been scraped", 10)
+
+ self.scraped_items.append(url.path_qs)
+ async with self._fetch_context(scrape_item):
+ await self.fetch(scrape_item)
+
+ def pre_check_scrape_item(self, scrape_item: ScrapeItem) -> None:
+ if not self.SKIP_PRE_CHECK and scrape_item.url.path == "/":
+ raise ValueError
+
+ @classmethod
+ def transform_url(cls, url: AbsoluteHttpURL) -> AbsoluteHttpURL:
+ """Transforms an URL before it reaches the fetch method
+
+ Override it to transform thumbnail URLs into full res URLs or URLs in an old unsupported format into a new one"""
+ return url
+
+ @final
+ @contextlib.asynccontextmanager
+ async def _fetch_context(self, scrape_item: ScrapeItem) -> AsyncGenerator[TaskID]:
+ with self.new_task_id(scrape_item.url) as task_id:
+ try:
+ self.pre_check_scrape_item(scrape_item)
+ yield task_id
+ except ValueError:
+ await self.raise_e(scrape_item, ScrapeError("Unknown URL path"))
+ except MaxChildrenError as e:
+ await self.raise_e(scrape_item, e)
+ finally:
+ pass
+
+ @error_handling_wrapper
+ def raise_e(self, scrape_item: ScrapeItem, exc: type[Exception] | Exception) -> None:
+ raise exc
+
+ @final
+ @contextlib.contextmanager
+ def new_task_id(self, url: AbsoluteHttpURL) -> Generator[TaskID]:
+ """Creates a new task_id (shows the URL in the UI and logs)"""
scrape_prefix = "Scraping"
if self.IS_FALLBACK_GENERIC:
scrape_prefix += " (unsupported domain)"
else:
scrape_prefix += f" [{self.FOLDER_DOMAIN}]"
-
- async with self._semaphore:
- self.waiting_items -= 1
- if item.url.path_qs not in self.scraped_items:
- log(f"{scrape_prefix}: {item.url}", 20)
- self.scraped_items.append(item.url.path_qs)
- await create_task_id(self.fetch)(self, item) # type: ignore
- else:
- log(f"Skipping {item.url} as it has already been scraped", 10)
+ log(f"{scrape_prefix}: {url}", 20)
+ task_id = self.manager.progress_manager.scraping_progress.add_task(url)
+ try:
+ yield task_id
+ finally:
+ self.manager.progress_manager.scraping_progress.remove_task(task_id)
@classmethod
def is_subdomain(cls, url: AbsoluteHttpURL, domain_to_compare: str | None = None) -> bool:
@@ -651,11 +672,6 @@ def _make_scrape_mapper_keys(cls: type[Crawler] | Crawler) -> tuple[str, ...]:
return tuple(sorted(host.removeprefix("www.") for host in hosts))
-def _pre_check_scrape_item(scrape_item: ScrapeItem) -> None:
- if scrape_item.url.path == "/":
- raise ValueError
-
-
def _make_custom_filename(stem: str, ext: str, extra_info: list[str], only_truncate_stem: bool) -> tuple[str, bool]:
truncate_len = constants.MAX_NAME_LENGTHS["FILE"] - len(ext)
invalid_extra_info_chars = False
@@ -724,3 +740,20 @@ def _validate_supported_paths(cls: type[Crawler]) -> None:
paths = (paths,)
for path in paths:
assert "`" not in path, f"{cls.__name__}, Invalid path {path_name}: {path}"
+
+
+def auto_task_id(
+ func: Callable[Concatenate[_CrawlerT, ScrapeItem, P], R | Coroutine[None, None, R]],
+) -> Callable[Concatenate[_CrawlerT, ScrapeItem, P], Coroutine[None, None, R]]:
+ """Autocreate a new `task_id` from the scrape_item of the method"""
+
+ @wraps(func)
+ async def wrapper(self: _CrawlerT, scrape_item: ScrapeItem, *args: P.args, **kwargs: P.kwargs) -> R:
+ await self.manager.states.RUNNING.wait()
+ with self.new_task_id(scrape_item.url):
+ result = func(self, scrape_item, *args, **kwargs)
+ if inspect.isawaitable(result):
+ return await result
+ return result
+
+ return wrapper
diff --git a/cyberdrop_dl/managers/hash_manager.py b/cyberdrop_dl/managers/hash_manager.py
index ba4242287..258fa1f34 100644
--- a/cyberdrop_dl/managers/hash_manager.py
+++ b/cyberdrop_dl/managers/hash_manager.py
@@ -29,7 +29,7 @@ class HashManager:
async def startup(self) -> None:
await self.hash_client.startup()
- async def hash_file(self, filename: str, hash_type: str) -> str:
+ async def hash_file(self, filename: Path | str, hash_type: str) -> str:
file_path = Path.cwd() / filename
async with aiofiles.open(file_path, "rb") as fp:
CHUNK_SIZE = 1024 * 1024 # 1MB
@@ -40,10 +40,11 @@ class HashManager:
filedata = await fp.read(CHUNK_SIZE)
return current_hasher.hexdigest()
- def _get_hasher(self, hash_type):
+ def _get_hasher(self, hash_type: str):
if hash_type == "xx128" and not self.xx_hasher:
raise ImportError("xxhash module is not installed")
- elif hash_type == "xxh128":
+ assert self.xx_hasher
+ if hash_type == "xxh128":
return self.xx_hasher()
elif hash_type == "md5":
return self.md5_hasher()
diff --git a/cyberdrop_dl/managers/real_debrid/api.py b/cyberdrop_dl/managers/real_debrid/api.py
index cc94059d5..ef3911796 100644
--- a/cyberdrop_dl/managers/real_debrid/api.py
+++ b/cyberdrop_dl/managers/real_debrid/api.py
@@ -56,10 +56,10 @@ class RealDebridApi:
self.torrents = Torrents(self)
self.hosts = Hosts(self)
self.settings = Settings(self)
- self.update_token(api_token)
+ self.update_token(api_token or "")
def get(self, path: str, *, entrypoint: URL = API_ENTRYPOINT, **query_params) -> dict:
- response = self._session.get(url=entrypoint / path, params=query_params)
+ response = self._session.get(url=str(entrypoint / path), params=query_params)
return self.handle_response(response)
def post(self, path: str, *, entrypoint: URL = API_ENTRYPOINT, **data) -> dict:
diff --git a/cyberdrop_dl/managers/realdebrid_manager.py b/cyberdrop_dl/managers/realdebrid_manager.py
index 5cad2eb0c..c7c65a4bb 100644
--- a/cyberdrop_dl/managers/realdebrid_manager.py
+++ b/cyberdrop_dl/managers/realdebrid_manager.py
@@ -13,8 +13,7 @@ from cyberdrop_dl.utils.logger import log
warnings.simplefilter(action="ignore", category=FutureWarning)
if TYPE_CHECKING:
- from yarl import URL
-
+ from cyberdrop_dl.data_structures.url_objects import AbsoluteHttpURL
from cyberdrop_dl.managers.manager import Manager
FOLDER_AS_PART = {"folder", "folders", "dir"}
@@ -50,26 +49,26 @@ class RealDebridManager:
log(f"Failed RealDebrid setup: {e}", 40)
self.enabled = False
- def is_supported_folder(self, url: URL) -> bool:
+ def is_supported_folder(self, url: AbsoluteHttpURL) -> bool:
match = self.folder_regex.search(str(url))
return bool(match)
- def is_supported_file(self, url: URL) -> bool:
+ def is_supported_file(self, url: AbsoluteHttpURL) -> bool:
match = self.file_regex.search(str(url))
return bool(match)
- def is_supported(self, url: URL) -> bool:
+ def is_supported(self, url: AbsoluteHttpURL) -> bool:
match = self.supported_regex.search(str(url))
return bool(match) or "real-debrid" in url.host.lower()
- def unrestrict_link(self, url: URL, password: str | None = None) -> URL:
- return self.api.unrestrict.link(url, password).get("download")
+ def unrestrict_link(self, url: AbsoluteHttpURL, password: str | None = None) -> AbsoluteHttpURL:
+ return self.api.unrestrict.link(url, password)["download"]
- def unrestrict_folder(self, url: URL) -> list[URL]:
+ def unrestrict_folder(self, url: AbsoluteHttpURL) -> list[AbsoluteHttpURL]:
return self.api.unrestrict.folder(url)
@staticmethod
- def _guess_folder_by_part(url: URL):
+ def _guess_folder_by_part(url: AbsoluteHttpURL) -> str | None:
for word in FOLDER_AS_PART:
if word in url.parts:
index = url.parts.index(word)
@@ -78,14 +77,14 @@ class RealDebridManager:
return None
@staticmethod
- def _guess_folder_by_query(url: URL):
+ def _guess_folder_by_query(url: AbsoluteHttpURL) -> str | None:
for word in FOLDER_AS_QUERY:
folder = url.query.get(word)
if folder:
return folder
return None
- def guess_folder(self, url: URL) -> str:
+ def guess_folder(self, url: AbsoluteHttpURL) -> str:
for guess_function in self._folder_guess_functions:
folder = guess_function(url)
if folder:
diff --git a/cyberdrop_dl/ui/progress/hash_progress.py b/cyberdrop_dl/ui/progress/hash_progress.py
index d1a935c5e..99192b387 100644
--- a/cyberdrop_dl/ui/progress/hash_progress.py
+++ b/cyberdrop_dl/ui/progress/hash_progress.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+from pathlib import Path
from typing import TYPE_CHECKING
from pydantic import ByteSize
@@ -8,8 +9,6 @@ from rich.panel import Panel
from rich.progress import BarColumn, Progress
if TYPE_CHECKING:
- from pathlib import Path
-
from cyberdrop_dl.managers.manager import Manager
@@ -55,9 +54,9 @@ class HashProgress:
"""Returns the progress bar."""
return Panel(self.removed_progress_group, border_style="green", padding=(1, 1))
- def update_currently_hashing(self, file: Path) -> None:
+ def update_currently_hashing(self, file: Path | str) -> None:
self.current_hashing_text.update(self.currently_hashing_task_id, description=f"[blue]{file}")
- file_size = ByteSize(file.stat().st_size)
+ file_size = ByteSize(Path(file).stat().st_size)
self.current_hashing_text.update(
self.currently_hashing_size_task_id,
description=f"[blue]{file_size.human_readable(decimal=True)}",
diff --git a/cyberdrop_dl/ui/prompts/basic_prompts.py b/cyberdrop_dl/ui/prompts/basic_prompts.py
index 3fc4a155c..78fadcc4d 100644
--- a/cyberdrop_dl/ui/prompts/basic_prompts.py
+++ b/cyberdrop_dl/ui/prompts/basic_prompts.py
@@ -1,3 +1,4 @@
+# type: ignore[reportPrivateImportUsage]
from pathlib import Path
from InquirerPy import inquirer
diff --git a/cyberdrop_dl/ui/prompts/user_prompts.py b/cyberdrop_dl/ui/prompts/user_prompts.py
index 39d527705..4e61d7847 100644
--- a/cyberdrop_dl/ui/prompts/user_prompts.py
+++ b/cyberdrop_dl/ui/prompts/user_prompts.py
@@ -1,3 +1,4 @@
+# type: ignore[reportPrivateImportUsage]
from __future__ import annotations
import asyncio
diff --git a/cyberdrop_dl/utils/database/tables/hash_table.py b/cyberdrop_dl/utils/database/tables/hash_table.py
index 9d534eed2..3fcdee0b6 100644
--- a/cyberdrop_dl/utils/database/tables/hash_table.py
+++ b/cyberdrop_dl/utils/database/tables/hash_table.py
@@ -1,7 +1,7 @@
from __future__ import annotations
from pathlib import Path
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, cast
from rich.console import Console
@@ -22,7 +22,7 @@ class HashTable:
"""Startup process for the HistoryTable."""
await self.create_hash_tables()
- async def create_hash_tables(self):
+ async def create_hash_tables(self) -> None:
await self.db_conn.execute(create_files)
await self.db_conn.execute(create_hash)
await self.db_conn.commit()
@@ -57,7 +57,9 @@ class HashTable:
console.print(f"Error checking file: {e}")
return None
- async def get_files_with_hash_matches(self, hash_value: str, size: int, hash_type: str | None = None) -> list:
+ async def get_files_with_hash_matches(
+ self, hash_value: str, size: int, hash_type: str | None = None
+ ) -> list[aiosqlite.Row]:
"""Retrieves a list of (folder, filename) tuples based on a given hash.
Args:
@@ -71,24 +73,19 @@ class HashTable:
try:
cursor = await self.db_conn.cursor()
if hash_type:
- await cursor.execute(
- "SELECT files.folder, files.download_filename,files.date FROM hash JOIN files ON hash.folder = files.folder AND hash.download_filename = files.download_filename WHERE hash.hash = ? AND files.file_size = ? AND hash.hash_type = ?;",
- (hash_value, size, hash_type),
- )
- return await cursor.fetchall()
+ query = "SELECT files.folder, files.download_filename,files.date FROM hash JOIN files ON hash.folder = files.folder AND hash.download_filename = files.download_filename WHERE hash.hash = ? AND files.file_size = ? AND hash.hash_type = ?;"
+
else:
- await cursor.execute(
- "SELECT files.folder, files.download_filename FROM hash JOIN files ON hash.folder = files.folder AND hash.download_filename = files.download_filename WHERE hash.hash = ? AND files.file_size = ? AND hash.hash_type = ?;",
- (hash_value, size, hash_type),
- )
- return await cursor.fetchall()
+ query = "SELECT files.folder, files.download_filename FROM hash JOIN files ON hash.folder = files.folder AND hash.download_filename = files.download_filename WHERE hash.hash = ? AND files.file_size = ? AND hash.hash_type = ?;"
+ await cursor.execute(query, (hash_value, size, hash_type))
+ return cast("list[aiosqlite.Row]", await cursor.fetchall())
except Exception as e:
console.print(f"Error retrieving folder and filename: {e}")
return []
async def insert_or_update_hash_db(
- self, hash_value: str, hash_type: str, file: str, original_filename: str, referer: URL
+ self, hash_value: str, hash_type: str, file: Path | str, original_filename: str | None, referer: URL | None
) -> bool:
"""Inserts or updates a record in the specified SQLite database.
@@ -104,10 +101,10 @@ class HashTable:
"""
hash = await self.insert_or_update_hashes(hash_value, hash_type, file)
- file = await self.insert_or_update_file(original_filename, referer, file)
- return file and hash
+ file_ = await self.insert_or_update_file(original_filename, referer, file)
+ return file_ and hash
- async def insert_or_update_hashes(self, hash_value, hash_type, file):
+ async def insert_or_update_hashes(self, hash_value: str, hash_type: str, file: Path | str) -> bool:
try:
full_path = Path(file).absolute()
download_filename = str(full_path.name)
@@ -123,9 +120,11 @@ class HashTable:
return False
return True
- async def insert_or_update_file(self, original_filename, referer, file):
+ async def insert_or_update_file(
+ self, original_filename: str | None, referer: URL | str | None, file: Path | str
+ ) -> bool:
try:
- referer = str(referer)
+ referer = str(referer) if referer else None
full_path = Path(file).absolute()
file_size = int(full_path.stat().st_size)
file_date = int(full_path.stat().st_mtime)
@@ -160,7 +159,7 @@ class HashTable:
return False
return True
- async def get_all_unique_hashes(self, hash_type=None) -> list:
+ async def get_all_unique_hashes(self, hash_type: str | None = None) -> list[str]:
"""Retrieves a list of hashes
Args:
diff --git a/cyberdrop_dl/utils/sorting.py b/cyberdrop_dl/utils/sorting.py
index e590bb96d..43c89d779 100644
--- a/cyberdrop_dl/utils/sorting.py
+++ b/cyberdrop_dl/utils/sorting.py
@@ -1,7 +1,6 @@
from __future__ import annotations
import asyncio
-import contextlib
import itertools
from datetime import datetime
from fractions import Fraction
@@ -15,7 +14,7 @@ from videoprops import get_audio_properties, get_video_properties
from cyberdrop_dl.constants import FILE_FORMATS
from cyberdrop_dl.utils import strings
-from cyberdrop_dl.utils.logger import log_with_color
+from cyberdrop_dl.utils.logger import log, log_with_color
from cyberdrop_dl.utils.utilities import purge_dir_tree
if TYPE_CHECKING:
@@ -135,11 +134,13 @@ class Sorter:
if not self.audio_format:
return
bitrate = duration = sample_rate = None
- with contextlib.suppress(RuntimeError, CalledProcessError):
+ try:
props: dict = get_audio_properties(str(file))
duration = int(float(props.get("duration", 0))) or None
bitrate = int(float(props.get("bit_rate", 0))) or None
sample_rate = int(float(props.get("sample_rate", 0))) or None
+ except (RuntimeError, CalledProcessError):
+ log(f"Unable to get audio properties of {file}")
if await self._process_file_move(
file,
@@ -157,12 +158,12 @@ class Sorter:
if not self.image_format:
return
height = resolution = width = None
- with (
- contextlib.suppress(PIL.UnidentifiedImageError, PIL.Image.DecompressionBombError), # type: ignore
- Image.open(file) as image,
- ): # type: ignore
- width, height = image.size
- resolution = f"{width}x{height}"
+ try:
+ with Image.open(file) as image:
+ width, height = image.size
+ resolution = f"{width}x{height}"
+ except (PIL.UnidentifiedImageError, PIL.Image.DecompressionBombError): # type: ignore
+ log(f"Unable to get some image properties of {file}")
if await self._process_file_move(
file,
@@ -181,20 +182,22 @@ class Sorter:
codec = duration = fps = height = resolution = width = None
- with contextlib.suppress(RuntimeError, CalledProcessError):
+ try:
props: dict = get_video_properties(str(file))
width = int(float(props.get("width", 0))) or None
height = int(float(props.get("height", 0))) or None
if width and height:
resolution = f"{width}x{height}"
- codec: str = props.get("codec_name")
+ codec: str | None = props.get("codec_name")
duration = int(float(props.get("duration", 0))) or None
fps = (
float(Fraction(props.get("avg_frame_rate", 0)))
if str(props.get("avg_frame_rate", 0)) not in {"0/0", "0"}
else None
)
+ except (RuntimeError, CalledProcessError):
+ log(f"Unable to get some video properties of {file}")
if fps is not None:
fps = str(int(fps)) if fps.is_integer() else f"{fps:.2f}"
diff --git a/cyberdrop_dl/utils/utilities.py b/cyberdrop_dl/utils/utilities.py
index 066fde187..8252d98a4 100644
--- a/cyberdrop_dl/utils/utilities.py
+++ b/cyberdrop_dl/utils/utilities.py
@@ -15,7 +15,7 @@ from dataclasses import Field, fields
from functools import lru_cache, partial, wraps
from pathlib import Path
from stat import S_ISREG
-from typing import TYPE_CHECKING, Any, ClassVar, ParamSpec, Protocol, TypeGuard, TypeVar
+from typing import TYPE_CHECKING, Any, ClassVar, Concatenate, ParamSpec, Protocol, TypeGuard, TypeVar
import aiofiles
import rich
@@ -51,6 +51,9 @@ if TYPE_CHECKING:
from cyberdrop_dl.downloader.downloader import Downloader
from cyberdrop_dl.managers.manager import Manager
+ CrawerOrDownloader = TypeVar("CrawerOrDownloader", bound=Crawler | Downloader)
+ Origin = TypeVar("Origin", bound=ScrapeItem | MediaItem | URL)
+
P = ParamSpec("P")
T = TypeVar("T")
@@ -86,19 +89,20 @@ class OGProperties(dict[str, str]):
def error_handling_wrapper(
- func: Callable[P, Coroutine[None, None, R]],
-) -> Callable[P, Coroutine[None, None, R | None]]:
+ func: Callable[Concatenate[CrawerOrDownloader, Origin, P], R | Coroutine[None, None, R]],
+) -> Callable[Concatenate[CrawerOrDownloader, Origin, P], Coroutine[None, None, R | None]]:
"""Wrapper handles errors for url scraping."""
@wraps(func)
- async def wrapper(*args, **kwargs) -> R | None:
- self: Crawler | Downloader = args[0]
- item: ScrapeItem | MediaItem | URL = args[1]
+ async def wrapper(self: CrawerOrDownloader, item: Origin, *args: P.args, **kwargs: P.kwargs) -> R | None:
link: URL = item if isinstance(item, URL) else item.url
origin = exc_info = None
link_to_show: URL | str = ""
try:
- return await func(*args, **kwargs)
+ result = func(self, item, *args, **kwargs)
+ if inspect.isawaitable(result):
+ return await result
+ return result
except TooManyCrawlerErrors:
return
except CDLBaseError as e:
@@ -129,11 +133,13 @@ def error_handling_wrapper(
origin = origin or get_origin(item)
is_downloader = getattr(self, "log_prefix", False)
if is_downloader:
- await self.write_download_error(item, error_log_msg, exc_info) # type: ignore
+ self.manager.task_group.create_task(self.write_download_error(item, error_log_msg, exc_info)) # type: ignore
return
log(f"Scrape Failed: {link_to_show} ({error_log_msg.main_log_msg})", 40, exc_info=exc_info)
- await self.manager.log_manager.write_scrape_error_log(link_to_show, error_log_msg.csv_log_msg, origin)
+ self.manager.task_group.create_task(
+ self.manager.log_manager.write_scrape_error_log(link_to_show, error_log_msg.csv_log_msg, origin)
+ )
self.manager.progress_manager.scrape_stats_progress.add_failure(error_log_msg.ui_failure)
return wrapper