Bulk asynchronous downloader for multiple file hosts
Python asynciobunkrcyberdropdownloaderdropboxfilestergofilegoogle-drivemediafiremegamega-nzonedrivepatreonpawchivepinterestpixeldraintransfer-ittwitchtwittervk
refactor: ignore more ruff rules (#1865)
NTFSvolume28f0f2a6588d
diff --git a/cyberdrop_dl/aio.py b/cyberdrop_dl/aio.pyindex abb7796d3..d6a2f2834 100644--- a/cyberdrop_dl/aio.py+++ b/cyberdrop_dl/aio.py@@ -263,7 +263,7 @@ def open() -> AsyncIOWrapper[str]: ...-def open(+def open( # noqa: PLR0913path: Path,mode: str = "r",buffering: int = -1,diff --git a/cyberdrop_dl/clients/downloads.py b/cyberdrop_dl/clients/downloads.pyindex ea95f8fb9..6f9ac2703 100644--- a/cyberdrop_dl/clients/downloads.py+++ b/cyberdrop_dl/clients/downloads.py@@ -76,7 +76,7 @@ class DownloadClient:) as resp:return await self._process_response(media_item, domain, resume_point, resp)- async def _process_response(+ async def _process_response( # noqa: C901self,media_item: MediaItem,domain: str,@@ -243,7 +243,7 @@ class DownloadClient:download_dir = self.get_download_dir(media_item)return download_dir / media_item.filename- async def get_final_file_info(self, media_item: MediaItem, domain: str) -> tuple[bool, bool]:+ async def get_final_file_info(self, media_item: MediaItem, domain: str) -> tuple[bool, bool]: # noqa: C901, PLR0912, PLR0915"""Complicated checker for if a file already exists, and was already downloaded."""media_item.path = self.get_file_location(media_item)part_suffix = media_item.path.suffix + constants.TempExt.PARTdiff --git a/cyberdrop_dl/clients/http.py b/cyberdrop_dl/clients/http.pyindex ac607b2b2..6a38bb5c0 100644--- a/cyberdrop_dl/clients/http.py+++ b/cyberdrop_dl/clients/http.py@@ -188,7 +188,7 @@ class HTTPClient:raise DownloadError(status=response.status)@contextlib.asynccontextmanager- async def request(+ async def request( # noqa: PLR0913self: object,url: AbsoluteHttpURL,/,@@ -222,7 +222,7 @@ class HTTPClient:yield resp@contextlib.asynccontextmanager- async def raw_request(+ async def raw_request( # noqa: PLR0913self,url: AbsoluteHttpURL,/,diff --git a/cyberdrop_dl/compat.py b/cyberdrop_dl/compat.pyindex 86a7e67c0..a3d2d37a6 100644--- a/cyberdrop_dl/compat.py+++ b/cyberdrop_dl/compat.py@@ -8,7 +8,6 @@ if TYPE_CHECKING:from collections.abc import Iterator-if sys.version_info < (3, 12):_EnumMemberT = TypeVar("_EnumMemberT", bound=enum.Enum)@@ -21,9 +20,10 @@ if sys.version_info < (3, 12):return Truetry:cls(member)- return Trueexcept ValueError:return False+ else:+ return Truedef __iter__(cls: type[_EnumMemberT]) -> Iterator[_EnumMemberT]: # type: ignore[reportGeneralTypeIssues] # pyright: ignore[reportGeneralTypeIssues]return (cls._member_map_[name] for name in cls._member_names_) # type: ignore[reportReturnType] # pyright: ignore[reportReturnType]diff --git a/cyberdrop_dl/cookies.py b/cyberdrop_dl/cookies.pyindex 53f43050a..8dfd4e883 100644--- a/cyberdrop_dl/cookies.py+++ b/cyberdrop_dl/cookies.py@@ -165,9 +165,10 @@ def _read_netscape_file(file: Path) -> MozillaCookieJar | None:cookie_jar = MozillaCookieJar(file)try:cookie_jar.load(ignore_discard=True)- return cookie_jarexcept OSError as e:logger.error(f"Unable to load cookies from '{file.name}':\n {e!s}")+ else:+ return cookie_jardef make_simple_cookie(cookie: Cookie, now: float) -> SimpleCookie:diff --git a/cyberdrop_dl/crawlers/__init__.py b/cyberdrop_dl/crawlers/__init__.pyindex 0e49697cc..9e1f5a463 100644--- a/cyberdrop_dl/crawlers/__init__.py+++ b/cyberdrop_dl/crawlers/__init__.py@@ -33,7 +33,7 @@ def _create_subclass(url: AbsoluteHttpURL | str, base_class: type[_CrawlerT]) ->"SUPPORTED_DOMAINS": (),"FOLDER_DOMAIN": "",}- return type(class_name, (base_class,), class_attributes) # type: ignore # pyright: ignore[reportReturnType]+ return type(class_name, (base_class,), class_attributes) # pyright: ignore[reportReturnType]def _make_crawler_name(input_string: str) -> str:diff --git a/cyberdrop_dl/crawlers/_forum.py b/cyberdrop_dl/crawlers/_forum.pyindex 6a85630f4..8159283af 100644--- a/cyberdrop_dl/crawlers/_forum.py+++ b/cyberdrop_dl/crawlers/_forum.py@@ -453,11 +453,8 @@ class HTMLMessageBoardCrawler(MessageBoardCrawler, is_abc=True):)if scrape_this_post:post_url = self.make_post_url(thread, current_post.id)- new_scrape_item = scrape_item.create_new(- thread.url,- possible_datetime=current_post.timestamp,- add_parent=post_url,- )+ new_scrape_item = scrape_item.create_new(thread.url, add_parent=post_url)+ new_scrape_item.uploaded_at = current_post.timestampself.create_task(self.post(new_scrape_item, current_post))try:scrape_item.add_children()@@ -599,7 +596,7 @@ def iter_links(links: Iterable[Tag], attribute: str) -> Iterable[str]:for link_tag in links:try:yield css.attr(link_tag, attribute)- except Exception: # noqa: BLE001+ except Exception: # noqa: BLE001, S112continuediff --git a/cyberdrop_dl/crawlers/_hls.py b/cyberdrop_dl/crawlers/_hls.pyindex 5ae5e3bc6..fcc874483 100644--- a/cyberdrop_dl/crawlers/_hls.py+++ b/cyberdrop_dl/crawlers/_hls.py@@ -23,7 +23,7 @@ class HLSParser(ABC):For multi variant m3u8, the best resolution will be automatically selected"""@abstractmethod- async def request_text(self, url: AbsoluteHttpURL, /, headers: Mapping[str, str] | None = None) -> str: ...+ async def request_text(self, url: AbsoluteHttpURL, /, *, headers: Mapping[str, str] | None = None) -> str: ...async def request_m3u8(self,diff --git a/cyberdrop_dl/crawlers/_kvs.py b/cyberdrop_dl/crawlers/_kvs.pyindex 74e5d2cee..13f63c253 100644--- a/cyberdrop_dl/crawlers/_kvs.py+++ b/cyberdrop_dl/crawlers/_kvs.py@@ -76,7 +76,7 @@ class KernelVideoSharingCrawler(Crawler, is_abc=True):return url / ""return url- async def fetch(self, scrape_item: ScrapeItem) -> None:+ async def fetch(self, scrape_item: ScrapeItem) -> None: # noqa: PLR0911match scrape_item.url.parts[1:]:case ["categories" | "tags", _]:return await self.collection(scrape_item)@@ -206,7 +206,7 @@ class KernelVideoSharingCrawler(Crawler, is_abc=True):src = self.parse_url(css.select(soup, Selector.PICTURE, "src"))await self.direct_file(scrape_item, src)- async def _ajax_pagination(+ async def _ajax_pagination( # noqa: PLR0913self,url: AbsoluteHttpURL,block_id: str,diff --git a/cyberdrop_dl/crawlers/ashemaletube.py b/cyberdrop_dl/crawlers/ashemaletube.pyindex 81ac34a38..fc6a3d9a6 100644--- a/cyberdrop_dl/crawlers/ashemaletube.py+++ b/cyberdrop_dl/crawlers/ashemaletube.py@@ -75,7 +75,7 @@ class AShemaleTubeCrawler(Crawler):NEXT_PAGE_SELECTOR: ClassVar[str] = _SELECTORS.NEXT_PAGE_RATE_LIMIT = 3, 10- async def fetch(self, scrape_item: ScrapeItem) -> None:+ async def fetch(self, scrape_item: ScrapeItem) -> None: # noqa: PLR0911if any(p in scrape_item.url.parts for p in ("creators", "profiles", "pornstars", "model")):if "galleries" in scrape_item.url.parts:return await self.gallery(scrape_item)diff --git a/cyberdrop_dl/crawlers/crawler.py b/cyberdrop_dl/crawlers/crawler.pyindex f032b3da2..cff83a638 100644--- a/cyberdrop_dl/crawlers/crawler.py+++ b/cyberdrop_dl/crawlers/crawler.py@@ -369,13 +369,15 @@ class Crawler(HTTPClientProxy, HLSParser, ABC):self._scraped_items.add(url.path_qs)+ if not self.ALLOW_EMPTY_PATH and url.path == "/":+ self.raise_exc(scrape_item, ScrapeError.unsupported())+ return+with self.new_task_id(scrape_item.url):try:- if not self.ALLOW_EMPTY_PATH and scrape_item.url.path == "/":- raise ValueErrorawait self.fetch(scrape_item)except ValueError:- self.raise_exc(scrape_item, ScrapeError("Unknown URL path"))+ self.raise_exc(scrape_item, ScrapeError.unsupported())except MaxChildrenError as e:self.raise_exc(scrape_item, e)@@ -433,7 +435,7 @@ class Crawler(HTTPClientProxy, HLSParser, ABC):await self.__write_to_jsonl(media_item)@final- async def handle_file(+ async def handle_file( # noqa: PLR0913self,url: AbsoluteHttpURL,scrape_item: ScrapeItem,@@ -854,7 +856,7 @@ class Crawler(HTTPClientProxy, HLSParser, ABC):return await self._request_m3u8(url, headers, media_type)@final- def create_custom_filename(+ def create_custom_filename( # noqa: PLR0913self,name: str, # can be the full name or just the stemext: str,diff --git a/cyberdrop_dl/crawlers/discourse/_discourse.py b/cyberdrop_dl/crawlers/discourse/_discourse.pyindex 94284c841..f4d43fa70 100644--- a/cyberdrop_dl/crawlers/discourse/_discourse.py+++ b/cyberdrop_dl/crawlers/discourse/_discourse.py@@ -97,10 +97,8 @@ class DiscourseCrawler(MessageBoardCrawler, is_generic=True):async def process_posts(self, scrape_item: ScrapeItem, topic: Topic) -> None:last_post_id = Noneasync for post in self.iter_posts(topic):- new_scrape_item = scrape_item.create_child(- self.PRIMARY_URL / post.path.removeprefix("/"),- possible_datetime=to_timestamp(post.created_at),- )+ new_scrape_item = scrape_item.create_child(self.PRIMARY_URL / post.path.removeprefix("/"))+ new_scrape_item.uploaded_at = to_timestamp(post.created_at)await self.post(new_scrape_item, post)last_post_id = post.idtry:@@ -141,7 +139,7 @@ class DiscourseCrawler(MessageBoardCrawler, is_generic=True):try:if link_str:yield self.parse_url(link_str)- except Exception: # noqa: BLE001+ except Exception: # noqa: BLE001, S112continuereturn iter_links()diff --git a/cyberdrop_dl/crawlers/eporner.py b/cyberdrop_dl/crawlers/eporner.pyindex 0f6e1fea6..071b7393a 100644--- a/cyberdrop_dl/crawlers/eporner.py+++ b/cyberdrop_dl/crawlers/eporner.py@@ -74,7 +74,7 @@ class EpornerCrawler(Crawler):NEXT_PAGE_SELECTOR: ClassVar[str] = Selector.NEXT_PAGE_RATE_LIMIT: ClassVar[RateLimit] = 2, 1- async def fetch(self, scrape_item: ScrapeItem) -> None:+ async def fetch(self, scrape_item: ScrapeItem) -> None: # noqa: PLR0911match scrape_item.url.parts[1:]:case [slug, *_] if slug.startswith("video-"):video_id = slug.removeprefix("video-")diff --git a/cyberdrop_dl/crawlers/invision/__init__.py b/cyberdrop_dl/crawlers/invision/__init__.pyindex 3bbf0ee06..34bda349f 100644--- a/cyberdrop_dl/crawlers/invision/__init__.py+++ b/cyberdrop_dl/crawlers/invision/__init__.py@@ -1,8 +1,52 @@-from ._invision import InvisionCrawler-from .bellazon import BellazonCrawler+"""Generic crawler for any Invision forum-INVISION_CRAWLERS: set[type[InvisionCrawler]] = {BellazonCrawler}+A Invision site has a tag with a `ipsCopyright` class and the text: "Powered By Invision"+"""+from __future__ import annotations-INVISION_CRAWLERS_MAP = {c.__name__: c for c in INVISION_CRAWLERS}-__all__ = list(INVISION_CRAWLERS_MAP.keys()) # type: ignore[reportUnsupportedDunderAll]+import dataclasses+from typing import TYPE_CHECKING, ClassVar++from cyberdrop_dl.crawlers._forum import HTMLMessageBoardCrawler+from cyberdrop_dl.crawlers.xenforo.xenforo import DEFAULT_XF_POST_SELECTORS, DEFAULT_XF_SELECTORS, XenforoCrawler+from cyberdrop_dl.utils import css++if TYPE_CHECKING:+ from cyberdrop_dl.crawlers._forum import MessageBoardSelectors+ from cyberdrop_dl.crawlers.crawler import SupportedPaths+++Selector = css.CssAttributeSelector+++DEFAULT_INVISION_POST_SELECTORS = dataclasses.replace(+ DEFAULT_XF_POST_SELECTORS,+ article="div[class*=ipsComment_content]",+ content="div.cPost_contentWrap",+ article_trash=(".message-signature", ".message-footer"),+ content_trash=("blockquote", "fauxBlockLink"),+ id=Selector("data-commentid", "data-commentid"),+ attachments=Selector("a[class*=ipsAttachLink]", "href"),+ images=Selector("a[class*=ipsAttachLink_image]", "href"),+ videos=Selector("video.ipsEmbeddedVideo source", "src"),+)+++DEFAULT_INVISION_SELECTORS = dataclasses.replace(+ DEFAULT_XF_SELECTORS,+ posts=DEFAULT_INVISION_POST_SELECTORS,+ title=Selector("span.ipsType_break.ipsContained span"),+ next_page=Selector("li.ipsPagination_next a[href]", "href"),+)+++class InvisionCrawler(HTMLMessageBoardCrawler, is_abc=True):+ SUPPORTED_PATHS: ClassVar[SupportedPaths] = XenforoCrawler.SUPPORTED_PATHS | {"**NOTE**": "base crawler: Invision"}+ SUPPORTS_THREAD_RECURSION: ClassVar[bool] = True+ SELECTORS: ClassVar[MessageBoardSelectors] = DEFAULT_INVISION_SELECTORS+ POST_URL_PART_NAME: ClassVar[str] = "comment"+ PAGE_URL_PART_NAME: ClassVar[str] = "page"+ IGNORE_EMBEDED_IMAGES_SRC: ClassVar[bool] = False+ LOGIN_USER_COOKIE_NAME: ClassVar[str] = "UNKNOWN" # TODO: Find out cookie name+ ATTACHMENT_HOSTS = ()diff --git a/cyberdrop_dl/crawlers/invision/_invision.py b/cyberdrop_dl/crawlers/invision/_invision.pydeleted file mode 100644index 2c6433c4d..000000000--- a/cyberdrop_dl/crawlers/invision/_invision.py+++ /dev/null@@ -1,52 +0,0 @@-"""Generic crawler for any Invision forum--A Invision site has a tag with a `ipsCopyright` class and the text: "Powered By Invision"-"""--from __future__ import annotations--import dataclasses-from typing import TYPE_CHECKING, ClassVar--from cyberdrop_dl.crawlers._forum import HTMLMessageBoardCrawler-from cyberdrop_dl.crawlers.xenforo.xenforo import DEFAULT_XF_POST_SELECTORS, DEFAULT_XF_SELECTORS, XenforoCrawler-from cyberdrop_dl.utils import css--if TYPE_CHECKING:- from cyberdrop_dl.crawlers._forum import MessageBoardSelectors- from cyberdrop_dl.crawlers.crawler import SupportedPaths---Selector = css.CssAttributeSelector---DEFAULT_INVISION_POST_SELECTORS = dataclasses.replace(- DEFAULT_XF_POST_SELECTORS,- article="div[class*=ipsComment_content]",- content="div.cPost_contentWrap",- article_trash=(".message-signature", ".message-footer"),- content_trash=("blockquote", "fauxBlockLink"),- id=Selector("data-commentid", "data-commentid"),- attachments=Selector("a[class*=ipsAttachLink]", "href"),- images=Selector("a[class*=ipsAttachLink_image]", "href"),- videos=Selector("video.ipsEmbeddedVideo source", "src"),-)---DEFAULT_INVISION_SELECTORS = dataclasses.replace(- DEFAULT_XF_SELECTORS,- posts=DEFAULT_INVISION_POST_SELECTORS,- title=Selector("span.ipsType_break.ipsContained span"),- next_page=Selector("li.ipsPagination_next a[href]", "href"),-)---class InvisionCrawler(HTMLMessageBoardCrawler, is_abc=True):- SUPPORTED_PATHS: ClassVar[SupportedPaths] = XenforoCrawler.SUPPORTED_PATHS | {"**NOTE**": "base crawler: Invision"} # type: ignore- SUPPORTS_THREAD_RECURSION: ClassVar[bool] = True- SELECTORS: ClassVar[MessageBoardSelectors] = DEFAULT_INVISION_SELECTORS- POST_URL_PART_NAME: ClassVar[str] = "comment"- PAGE_URL_PART_NAME: ClassVar[str] = "page"- IGNORE_EMBEDED_IMAGES_SRC: ClassVar[bool] = False- LOGIN_USER_COOKIE_NAME: ClassVar[str] = "UNKNOWN" # TODO: Find out cookie name- ATTACHMENT_HOSTS = ()diff --git a/cyberdrop_dl/crawlers/invision/bellazon.py b/cyberdrop_dl/crawlers/invision/bellazon.pyindex 6a82ae75e..f15695d78 100644--- a/cyberdrop_dl/crawlers/invision/bellazon.py+++ b/cyberdrop_dl/crawlers/invision/bellazon.py@@ -4,7 +4,7 @@ from typing import ClassVarfrom cyberdrop_dl.url_objects import AbsoluteHttpURL-from ._invision import InvisionCrawler+from . import InvisionCrawlerclass BellazonCrawler(InvisionCrawler):diff --git a/cyberdrop_dl/crawlers/kemono.py b/cyberdrop_dl/crawlers/kemono.pyindex ae18bff13..c4f9ba481 100644--- a/cyberdrop_dl/crawlers/kemono.py+++ b/cyberdrop_dl/crawlers/kemono.py@@ -224,7 +224,7 @@ class KemonoBaseCrawler(Crawler, is_abc=True):if getattr(self, "API_ENTRYPOINT", None):await self._get_usernames(self.API_ENTRYPOINT / "creators")- async def fetch(self, scrape_item: ScrapeItem) -> None:+ async def fetch(self, scrape_item: ScrapeItem) -> None: # noqa: PLR0911match scrape_item.url.parts[1:]:case [service, "user", _, "post", _] if service in self.SERVICES:return await self.post(scrape_item)diff --git a/cyberdrop_dl/crawlers/mega_nz.py b/cyberdrop_dl/crawlers/mega_nz.pyindex 7f8d738e3..fdc5fbbb3 100644--- a/cyberdrop_dl/crawlers/mega_nz.py+++ b/cyberdrop_dl/crawlers/mega_nz.py@@ -150,7 +150,8 @@ class MegaNzCrawler(Crawler, db_path="path_qs_frag"):if await self.check_complete_from_referer(canonical_url):continue- child_item = scrape_item.create_child(canonical_url, possible_datetime=file.created_at)+ child_item = scrape_item.create_child(canonical_url)+ child_item.uploaded_at = file.created_atfor part in path.parent.parts[1:]:child_item.add_to_parent_title(part)diff --git a/cyberdrop_dl/crawlers/pixeldrain.py b/cyberdrop_dl/crawlers/pixeldrain.pyindex 450d02eeb..c8afae296 100644--- a/cyberdrop_dl/crawlers/pixeldrain.py+++ b/cyberdrop_dl/crawlers/pixeldrain.py@@ -176,7 +176,7 @@ class PixelDrainCrawler(Crawler):scrape_item.add_children()@error_handling_wrapper- async def filesystem(self, scrape_item: ScrapeItem, path: str) -> None:+ async def filesystem(self, scrape_item: ScrapeItem, path: str) -> None: # noqa: C901# https://github.com/Fornaxian/pixeldrain_web/blob/8e5ecfc5ce44c0b2b4fafdf9e8201dfc98395e88/svelte/src/filesystem/FilesystemAPI.tsorigin = scrape_item.url.origin()@@ -275,7 +275,7 @@ class PixelDrainCrawler(Crawler):for line in text.splitlines():try:link = self.parse_url(line)- except Exception: # noqa: BLE001+ except Exception: # noqa: BLE001, S112continuenew_scrape_item = scrape_item.create_child(link)self.handle_external_links(new_scrape_item)diff --git a/cyberdrop_dl/crawlers/pornhub.py b/cyberdrop_dl/crawlers/pornhub.pyindex 05739ca3c..dbf672b6c 100644--- a/cyberdrop_dl/crawlers/pornhub.py+++ b/cyberdrop_dl/crawlers/pornhub.py@@ -132,7 +132,7 @@ class PornHubCrawler(Crawler):keys = ("age_verified", "accessPH", "accessAgeDisclaimerPH", "accessAgeDisclaimerUK", "expiredEnterModalShown")self.update_cookies(dict.fromkeys(keys, 1))- async def fetch(self, scrape_item: ScrapeItem) -> None:+ async def fetch(self, scrape_item: ScrapeItem) -> None: # noqa: PLR0911match scrape_item.url.parts[1:]:case ["user" | "channel" | "channels" | "model" | "pornstar" as type_, name, *rest]:profile = Profile.new(type_, name, rest)diff --git a/cyberdrop_dl/crawlers/porntrex.py b/cyberdrop_dl/crawlers/porntrex.pyindex d09b54d77..689f1c8e7 100644--- a/cyberdrop_dl/crawlers/porntrex.py+++ b/cyberdrop_dl/crawlers/porntrex.py@@ -139,7 +139,7 @@ class PorntrexCrawler(Crawler):for _, new_scrape_item in self.iter_children(scrape_item, soup, Selector.ALBUMS, new_title_part="albums"):self.create_task(self.run(new_scrape_item))- async def proccess_additional_pages(self, scrape_item: ScrapeItem, last_page: int, **kwargs: str) -> None:+ async def proccess_additional_pages(self, scrape_item: ScrapeItem, last_page: int, **kwargs: str) -> None: # noqa: C901if last_page == 1:returnblock_id: str = "list_videos_common_videos_list_norm"diff --git a/cyberdrop_dl/crawlers/voe_sx.py b/cyberdrop_dl/crawlers/voe_sx.pyindex 4788598ba..1f65f7473 100644--- a/cyberdrop_dl/crawlers/voe_sx.py+++ b/cyberdrop_dl/crawlers/voe_sx.py@@ -182,11 +182,12 @@ def _load_json(json_content: str) -> Any:try:data = json.loads(json_content)- if isinstance(data, list) and len(data) == 1:- return _decrypt_json(data[0])- return data+ if type(data) is list and len(data) == 1:+ data = _decrypt_json(data[0])except json.JSONDecodeError:return None+ else:+ return datadef _decrypt_json(encrypted_json: str) -> Any:diff --git a/cyberdrop_dl/crawlers/wordpress/__init__.py b/cyberdrop_dl/crawlers/wordpress/__init__.pyindex 2d9b1634d..513659546 100644--- a/cyberdrop_dl/crawlers/wordpress/__init__.py+++ b/cyberdrop_dl/crawlers/wordpress/__init__.py@@ -185,7 +185,7 @@ class WordPressBaseCrawler(Crawler, is_abc=True):for link_str in dict.fromkeys(iterable):try:yield self.parse_url(link_str)- except Exception: # noqa: BLE001+ except Exception: # noqa: BLE001, S112continuediff --git a/cyberdrop_dl/crawlers/xhamster.py b/cyberdrop_dl/crawlers/xhamster.pyindex a23ee5973..b70c84a58 100644--- a/cyberdrop_dl/crawlers/xhamster.py+++ b/cyberdrop_dl/crawlers/xhamster.py@@ -291,7 +291,7 @@ def _parse_video(initials: dict[str, Any]) -> Video:)-def _parse_xplayer_sources(xplayer_sources: dict[str, Any]) -> Iterable[Format]:+def _parse_xplayer_sources(xplayer_sources: dict[str, Any]) -> Iterable[Format]: # noqa: C901if not xplayer_sources:return@@ -336,7 +336,7 @@ def _ensure_signed_32int(int32: int) -> int:return unsigned_32_bit-def _make_decoder(algo: int, seed: int) -> Callable[[], int]:+def _make_decoder(algo: int, seed: int) -> Callable[[], int]: # noqa: C901, PLR0915current_step = seedif algo == 1:@@ -424,9 +424,10 @@ def _make_decoder(algo: int, seed: int) -> Callable[[], int]:def _is_hex(hex_string: str) -> bool:try:int(hex_string, 16)- return Trueexcept ValueError:return False+ else:+ return Truedef _decode_hex_url(encrypted_url: str) -> str:diff --git a/cyberdrop_dl/csv_logs.py b/cyberdrop_dl/csv_logs.pyindex 38e36e066..db0873948 100644--- a/cyberdrop_dl/csv_logs.py+++ b/cyberdrop_dl/csv_logs.py@@ -163,7 +163,7 @@ class CSVLogsManager:await asyncio.to_thread(update)-def _update_last_forum_post(input_file: Path, last_post_log: Path) -> None:+def _update_last_forum_post(input_file: Path, last_post_log: Path) -> None: # noqa: C901log_spacer()logger.info("Updating Last Forum Posts...\n")@@ -188,7 +188,7 @@ def _update_last_forum_post(input_file: Path, last_post_log: Path) -> None:with last_post_log.open(encoding="utf8") as f:reader = csv.DictReader(f.readlines())for row in reader:- new_url = base_url = row["url"].strip().removesuffix("/") # type: ignore+ new_url = base_url = row["url"].strip().removesuffix("/")if "https" in new_url and "/post-" in new_url:base_url = new_url.rsplit("/post", 1)[0]diff --git a/cyberdrop_dl/database/tables/hash.py b/cyberdrop_dl/database/tables/hash.pyindex 603a183eb..385a2e7df 100644--- a/cyberdrop_dl/database/tables/hash.py+++ b/cyberdrop_dl/database/tables/hash.py@@ -56,8 +56,8 @@ class HashTable:if row := await cursor.fetchone():return row[0]- except Exception as e:- logger.exception(f"Error checking file: {e}")+ except Exception:+ logger.exception("Error checking file")async def get_files_with_hash_matches(self, hash_value: str, size: int, hash_type: str | None = None@@ -134,8 +134,8 @@ class HashTable:folder = str(full_path.parent)await self.db_conn.execute(query, (hash_value, hash_type, folder, download_filename, hash_value))await self.db_conn.commit()- except Exception as e:- logger.exception(f"Error inserting/updating record: {e}")+ except Exception:+ logger.exception("Error inserting/updating record")return Falsereturn True@@ -171,8 +171,8 @@ class HashTable:),)await self.db_conn.commit()- except Exception as e:- logger.exception(f"Error inserting/updating record: {e}")+ except Exception:+ logger.exception("Error inserting/updating record")return Falsereturn True@@ -195,6 +195,6 @@ class HashTable:cursor = await self.db_conn.execute(query, params)rows = await cursor.fetchall()return [row[0] for row in rows]- except Exception as e:- logger.exception(f"Error retrieving folder and filename: {e}")+ except Exception:+ logger.exception("Error retrieving folder and filename")return []diff --git a/cyberdrop_dl/database/tables/history.py b/cyberdrop_dl/database/tables/history.pyindex 37c7eefc0..6caebe6f4 100644--- a/cyberdrop_dl/database/tables/history.py+++ b/cyberdrop_dl/database/tables/history.py@@ -231,8 +231,8 @@ class HistoryTable:while rows := await cursor.fetchmany(_FETCH_MANY_SIZE):yield cast("list[Row]", rows)- except Exception as e:- logger.exception(f"Error getting bunkr failed via size: {e}")+ except Exception:+ logger.exception("Error getting bunkr failed via size")async def get_all_bunkr_failed_via_hash(self) -> AsyncGenerator[list[Row]]:query = """@@ -246,8 +246,8 @@ class HistoryTable:while rows := await cursor.fetchmany(_FETCH_MANY_SIZE):yield cast("list[Row]", rows)- except Exception as e:- logger.exception(f"Error getting bunkr failed via hash: {e}")+ except Exception:+ logger.exception("Error getting bunkr failed via hash")async def fix_primary_keys(self) -> None:domain_column, *_ = await self._get_media_table_columns()@@ -294,9 +294,9 @@ class HistoryTable:async def fix_domains(db_conn: aiosqlite.Connection) -> None:- logger.info("Updating old domains")+ logger.info("Updating old database domains")updates = "\n".join(- f"UPDATE OR REPLACE media SET domain = '{current}' WHERE domain = '{old}';"+ f"UPDATE OR REPLACE media SET domain = '{current}' WHERE domain = '{old}';" # noqa: S608for current, old in [("bunkr", "bunkrr"),("jpg5.su", "sharex"),@@ -311,7 +311,7 @@ async def fix_domains(db_conn: aiosqlite.Connection) -> None:async def fix_referers(db_conn: aiosqlite.Connection) -> None:from cyberdrop_dl.crawlers import cyberdrop, jpg5, redgifs, turbovid- logger.info("Updating old referers")+ logger.info("Updating old database referers")def try_wrap(fn: Callable[..., _T]) -> Callable[..., _T]:def call(*args: Any, **kwargs: Any) -> _T:diff --git a/cyberdrop_dl/database/transfer.py b/cyberdrop_dl/database/transfer.pyindex 6defe954d..0092e3b7f 100644--- a/cyberdrop_dl/database/transfer.py+++ b/cyberdrop_dl/database/transfer.py@@ -5,6 +5,7 @@ import loggingimport sqlite3import sysfrom pathlib import Path+from typing import LiteralStringfrom cyberdrop_dl.database import Database, connectfrom cyberdrop_dl.database.tables.history import fix_domains, fix_referers@@ -16,9 +17,9 @@ from cyberdrop_dl.utils.filepath import sanitize_filenamelogger = logging.getLogger(__name__)-def _get_table_names(conn: sqlite3.Connection, schema: str = "main") -> set[str]:- rows = conn.execute(f"SELECT name FROM {schema}.sqlite_master WHERE type='table'").fetchall()- return {r[0] for r in rows}+def _get_table_names(conn: sqlite3.Connection, schema: LiteralString = "main") -> set[str]:+ cursor = conn.execute(f"SELECT name FROM {schema}.sqlite_master WHERE type='table'") # noqa: S608+ return {r[0] for r in cursor.fetchall()}def _get_column_names(conn: sqlite3.Connection, table: str, schema: str = "main") -> set[str]:@@ -98,7 +99,7 @@ def _transfer_table(new_conn: sqlite3.Connection, table: str) -> None:select_sql = ", ".join(select_exprs)logger.info("_transfer_table: old.%s -> %s", table, table)- new_conn.execute(f'INSERT OR IGNORE INTO "{table}" ({cols_sql}) SELECT {select_sql} FROM old."{table}"')+ new_conn.execute(f'INSERT OR IGNORE INTO "{table}" ({cols_sql}) SELECT {select_sql} FROM old."{table}"') # noqa: S608def _transfer_media_to_files(new_conn: sqlite3.Connection) -> None:@@ -127,7 +128,7 @@ def _transfer_media_to_files(new_conn: sqlite3.Connection) -> None:CAST(strftime('%s', "created_at") AS INTEGER)FROM old."media"WHERE "download_path" IS NOT NULL- """+ """ # noqa: S608)diff --git a/cyberdrop_dl/dedupe.py b/cyberdrop_dl/dedupe.pyindex 57c0a65d3..9cb36158a 100644--- a/cyberdrop_dl/dedupe.py+++ b/cyberdrop_dl/dedupe.py@@ -93,7 +93,6 @@ async def _delete_file(path: Path, *, to_trash: bool) -> bool:try:await coro- return Trueexcept FileNotFoundError:return Falseexcept OSError as e:@@ -101,6 +100,8 @@ async def _delete_file(path: Path, *, to_trash: bool) -> bool:if "file not found" in str(e).casefold():return Falseraise+ else:+ return Truedef _filter_db_matches(db_matches: Iterable[sqlite3.Row], base_dir: Path) -> Generator[Path]:diff --git a/cyberdrop_dl/downloader/hls.py b/cyberdrop_dl/downloader/hls.pyindex 9ff79e6d6..54b6622b0 100644--- a/cyberdrop_dl/downloader/hls.py+++ b/cyberdrop_dl/downloader/hls.py@@ -161,8 +161,8 @@ async def download(media_item: MediaItem, rendition: Rendition, download_fn: Dowreturn Nonetry:subs = await download(rendition.subtitle)- except Exception as e:- logger.exception(f"Unable to download subtitles for {media_item.url}, Skipping. {e!r}")+ except Exception:+ logger.exception(f"Unable to download subtitles for {media_item.url}, Skipping")else:logger.warning(f"Found subtitles for {media_item.url}, but CDL is currently unable to merge them. Subtitle were saved at '{subs}'"diff --git a/cyberdrop_dl/downloader/http.py b/cyberdrop_dl/downloader/http.pyindex 2c6d2bca6..226419ec5 100644--- a/cyberdrop_dl/downloader/http.py+++ b/cyberdrop_dl/downloader/http.py@@ -258,7 +258,7 @@ class Downloader:async with _exclusive_lock(media_item):return bool(await self.download(media_item))- async def _download(self, media_item: MediaItem) -> bool | None:+ async def _download(self, media_item: MediaItem) -> bool | None: # noqa: C901"""Downloads the media item."""url_as_str = str(media_item.url)if url_as_str in _KNOWN_BAD_URLS:@@ -269,13 +269,6 @@ class Downloader:media_item.duration = await self.manager.database.history.get_duration(self.domain, media_item)await self.check_file_can_download(media_item)downloaded = await self.client.download_file(self.domain, media_item)- if downloaded:- 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.scrape_mapper.tui.files.stats.completed += 1- logger.info(f"Download finished: {media_item.url}")- return downloadedexcept SkipDownloadError as e:if not media_item.is_segment:@@ -304,6 +297,15 @@ class Downloader:message = str(e)raise DownloadError(ui_message, message, retry=True) from e+ else:+ if downloaded:+ 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.scrape_mapper.tui.files.stats.completed += 1+ logger.info(f"Download finished: {media_item.url}")+ return downloaded+def _is_allowed_filetype(media_item: MediaItem, config: Config) -> bool:ignore_options = config.settings.ignore_optionsdiff --git a/cyberdrop_dl/exceptions.py b/cyberdrop_dl/exceptions.pyindex 69b9ca011..f39fcc6a5 100644--- a/cyberdrop_dl/exceptions.py+++ b/cyberdrop_dl/exceptions.py@@ -189,6 +189,10 @@ class ScrapeError(CDLBaseError):ui_failure = create_error_msg(status)super().__init__(ui_failure, message=message, status=status, origin=origin)+ @staticmethod+ def unsupported() -> ScrapeError:+ return ScrapeError("Unknown URL path")+class InvalidURLError(ScrapeError):def __init__(diff --git a/cyberdrop_dl/ffmpeg.py b/cyberdrop_dl/ffmpeg.pyindex 1c47b27ca..0d3bf59b2 100644--- a/cyberdrop_dl/ffmpeg.py+++ b/cyberdrop_dl/ffmpeg.py@@ -50,9 +50,10 @@ _FFPROBE_CALL_PREFIX = (def is_installed() -> bool:try:_check()- return Trueexcept RuntimeError:return False+ else:+ return Truedef _check() -> None:diff --git a/cyberdrop_dl/hasher.py b/cyberdrop_dl/hasher.pyindex 3acf667f3..4d3a0e7a8 100644--- a/cyberdrop_dl/hasher.py+++ b/cyberdrop_dl/hasher.py@@ -122,8 +122,8 @@ class Hasher:media_item.path, media_item.original_filename, media_item.referer)await self.save_hash_data(media_item, hash_value)- except Exception as e:- logger.exception(f"After hash processing failed: '{media_item.path}' with error {e}")+ except Exception:+ logger.exception("After hash processing failed: '%s'", media_item.path)async def update_db_and_retrive_hash(self,@@ -186,8 +186,8 @@ class Hasher:original_filename,referer,)- except Exception as e:- logger.exception(f"Error hashing '{file}' : {e}")+ except Exception:+ logger.exception("Error hashing '%s'", file)else:return hash_valuediff --git a/cyberdrop_dl/logs.py b/cyberdrop_dl/logs.pyindex 9115c7ce1..eda70c136 100644--- a/cyberdrop_dl/logs.py+++ b/cyberdrop_dl/logs.py@@ -205,7 +205,7 @@ def _threaded_logger(@contextlib.contextmanager-def _enter_context(context_var: ContextVar[_T], value: _T) -> Generator[None]:+def _enter_context(context_var: ContextVar[_T], value: _T, /) -> Generator[None]:token = context_var.set(value)try:yield@@ -323,7 +323,7 @@ def setup_file_logging(file: Path, /, *, level: int = logging.DEBUG) -> Generatoimport megaif "pytest" not in sys.modules:- logging.captureWarnings(True)+ logging.captureWarnings(capture=True)with (_setup_debug_logger() as debug_log_file,diff --git a/cyberdrop_dl/mediaprops.py b/cyberdrop_dl/mediaprops.pyindex 95c33ad9d..b7596cb2b 100644--- a/cyberdrop_dl/mediaprops.py+++ b/cyberdrop_dl/mediaprops.py@@ -67,7 +67,7 @@ class Resolution(NamedTuple):return Fraction(self.width, self.height)@staticmethod- def parse(url_number_or_string: yarl.URL | str | int | None, /) -> Resolution:+ def parse(url_number_or_string: yarl.URL | str | int | None, /) -> Resolution: # noqa: PLR0911if url_number_or_string is None:return UNKNOWN_RESOLUTIONdiff --git a/cyberdrop_dl/scrape_mapper.py b/cyberdrop_dl/scrape_mapper.pyindex c470b1e97..690233e6e 100644--- a/cyberdrop_dl/scrape_mapper.py+++ b/cyberdrop_dl/scrape_mapper.py@@ -251,10 +251,10 @@ class ScrapeMapper:try:await self._direct_http.fetch(scrape_item)- return-except (NoExtensionError, ValueError):pass+ else:+ returnif self._jdownloader.is_enabled_for(scrape_item.url):logger.info(f"Sending unsupported URL to JDownloader: {scrape_item.url}")diff --git a/cyberdrop_dl/url_objects.py b/cyberdrop_dl/url_objects.pyindex d5a022911..9a45f1ef7 100644--- a/cyberdrop_dl/url_objects.py+++ b/cyberdrop_dl/url_objects.py@@ -5,7 +5,6 @@ import contextlibimport copyimport datetimeimport logging-from contextvars import ContextVar, Tokenfrom dataclasses import asdict, dataclass, fieldfrom enum import IntEnumfrom pathlib import Path@@ -116,7 +115,6 @@ FILE_HOST_PROFILE = ScrapeItemType.FILE_HOST_PROFILEFILE_HOST_ALBUM = ScrapeItemType.FILE_HOST_ALBUM-CURRENT_URL: ContextVar[AbsoluteHttpURL] = ContextVar("_CURRENT_URL")logger = logging.getLogger(__name__)@@ -146,8 +144,8 @@ class MediaItem:parent_threads: set[AbsoluteHttpURL] = field(default_factory=set)attempts: int = 0- partial_file: Path = None # type: ignore- path: Path = None # type: ignore+ partial_file: Path = None # pyright: ignore[reportAssignmentType]+ path: Path = None # pyright: ignore[reportAssignmentType]hash: str | None = Nonedownloaded: bool = field(default=False)@@ -185,7 +183,7 @@ class MediaItem:return self.path.parent / f"{self.base64_id}.part"@staticmethod- def from_item(+ def from_item( # noqa: PLR0913origin: ScrapeItem | MediaItem,url: AbsoluteHttpURL,domain: str,@@ -240,16 +238,6 @@ class ScrapeItem:children_limits: list[int] = field(default_factory=list, init=False)password: str | None = field(default=None, init=False)- _token: Token[AbsoluteHttpURL] | None = field(default=None, init=False)-- def __enter__(self) -> Self:- self._token = CURRENT_URL.set(self.url)- return self-- def __exit__(self, *_: object) -> None:- assert self._token- CURRENT_URL.reset(self._token)-@contextlib.contextmanagerdef track_changes(self) -> Generator[Self]:old_url = self.url@@ -260,7 +248,7 @@ class ScrapeItem:logger.info(f"URL transformation applied: \n {old_url = !s}\n new_url = {self.url}")def __repr__(self) -> str:- return f"{type(self).__name__}(url={self.url!r}, parent_title={self.parent_title!r}, possible_datetime={self.uploaded_at!r}"+ return f"{type(self).__name__}(url={self.url!r}, parent_title={self.parent_title!r}, uploaded_at={self.uploaded_at!r}"def __post_init__(self) -> None:self.password = self.url.query.get("password")@@ -336,7 +324,6 @@ class ScrapeItem:new_title_part: str = "",part_of_album: bool = False,album_id: str | None = None,- possible_datetime: int | None = None,add_parent: AbsoluteHttpURL | bool | None = None,) -> Self:"""Creates a scrape item."""@@ -355,38 +342,29 @@ class ScrapeItem:scrape_item.url = urlscrape_item.part_of_album = part_of_album or scrape_item.part_of_album- scrape_item.uploaded_at = possible_datetime or scrape_item.uploaded_atscrape_item.album_id = album_id or scrape_item.album_idreturn scrape_item- def create_child(- self,- url: AbsoluteHttpURL,- *,- new_title_part: str = "",- album_id: str | None = None,- possible_datetime: int | None = None,- ) -> Self:+ def create_child(self, url: AbsoluteHttpURL, *, new_title_part: str = "", album_id: str | None = None) -> Self:return self.create_new(url,part_of_album=True,add_parent=True,new_title_part=new_title_part,album_id=album_id,- possible_datetime=possible_datetime,)def setup_as_album(self: ScrapeItem, title: str, *, album_id: str | None = None) -> None:- return self.setup_as(title, type_=FILE_HOST_ALBUM, album_id=album_id)+ return self.setup_as(title, FILE_HOST_ALBUM, album_id=album_id)def setup_as_profile(self: ScrapeItem, title: str, *, album_id: str | None = None) -> None:- return self.setup_as(title, type_=FILE_HOST_PROFILE, album_id=album_id)+ return self.setup_as(title, FILE_HOST_PROFILE, album_id=album_id)def setup_as_forum(self: ScrapeItem, title: str, *, album_id: str | None = None) -> None:- return self.setup_as(title, type_=FORUM, album_id=album_id)+ return self.setup_as(title, FORUM, album_id=album_id)def setup_as_post(self: ScrapeItem, title: str, *, album_id: str | None = None) -> None:- return self.setup_as(title, type_=FORUM_POST, album_id=album_id)+ return self.setup_as(title, FORUM_POST, album_id=album_id)@propertydef origin(self) -> AbsoluteHttpURL | None:@@ -409,10 +387,7 @@ class ScrapeItem:def copy(self) -> Self:"""Returns a deep copy of this scrape_item"""- self._token, token = None, self._token- me = copy.deepcopy(self)- self._token = token- return me+ return copy.deepcopy(self)class QueryDatetimeRange(NamedTuple):diff --git a/cyberdrop_dl/utils/__init__.py b/cyberdrop_dl/utils/__init__.pyindex 426a9d964..71956a40f 100644--- a/cyberdrop_dl/utils/__init__.py+++ b/cyberdrop_dl/utils/__init__.py@@ -78,12 +78,11 @@ class DictDataclass(Dataclass, Protocol):@contextlib.contextmanager-def error_handling_context(self: _HasManager, item: ScrapeItem | MediaItem | yarl.URL) -> Generator[None]:+def error_handling_context(self: _HasManager, item: ScrapeItem | MediaItem | yarl.URL) -> Generator[None]: # noqa: C901, PLR0912link: yarl.URL = item if isinstance(item, yarl.URL) else item.urlerror_log_msg = origin = exc_info = Nonelink_to_show: yarl.URL | str = ""is_segment: bool = getattr(item, "is_segment", False)- is_downloader: bool = bool(getattr(self, "log_prefix", False))try:yieldexcept TooManyCrawlerErrors:@@ -137,8 +136,19 @@ def error_handling_context(self: _HasManager, item: ScrapeItem | MediaItem | yarif error_log_msg is None or is_segment:return- link_to_show = link_to_show or link+ _log_error(self, link_to_show or link, item, error_log_msg, exc_info, origin)+++def _log_error( # noqa: PLR0913+ self: _HasManager,+ link_to_show: yarl.URL | str,+ item: ScrapeItem | MediaItem | yarl.URL,+ error_log_msg: ErrorLogMessage,+ exc_info: Exception | None,+ origin: ScrapeItem | MediaItem | yarl.URL | Path | None,+) -> None:origin = origin or get_origin(item)+ is_downloader = bool(getattr(self, "log_prefix", False))if is_downloader:self, item = cast("Downloader", self), cast("MediaItem", item)logger.error(@@ -151,7 +161,7 @@ def error_handling_context(self: _HasManager, item: ScrapeItem | MediaItem | yarreturnlogger.error(f"Scrape Failed: {link_to_show} ({error_log_msg.main_log_msg})", exc_info=exc_info)- self.manager.logs.write_scrape_error(link_to_show, error_log_msg.csv_log_msg, origin)+ self.manager.logs.write_scrape_error(link_to_show, error_log_msg.csv_log_msg, origin) # pyright: ignore[reportArgumentType]self.manager.scrape_mapper.tui.scrape_errors.add(error_log_msg.ui_failure)diff --git a/cyberdrop_dl/utils/_path_traverse.py b/cyberdrop_dl/utils/_path_traverse.pyindex f7859b7cb..290d4fd3e 100644--- a/cyberdrop_dl/utils/_path_traverse.py+++ b/cyberdrop_dl/utils/_path_traverse.py@@ -60,6 +60,7 @@ def delete_empty_files_and_folders_in_place(dirname: Path | str) -> bool:return Falsetry:os.rmdir(dirname) # noqa: PTH106- return Trueexcept OSError:return False+ else:+ return Truediff --git a/cyberdrop_dl/utils/json.py b/cyberdrop_dl/utils/json.pyindex b26958de5..7955ef95c 100644--- a/cyberdrop_dl/utils/json.py+++ b/cyberdrop_dl/utils/json.py@@ -45,7 +45,7 @@ class _DataclassInstance(Protocol):__dataclass_fields__: ClassVar[dict[str, dataclasses.Field[Any]]]-def default(obj: object, /) -> Any:+def default(obj: object, /) -> Any: # noqa: PLR0911if isinstance(obj, datetime.date):return obj.isoformat()if isinstance(obj, enum.Enum):diff --git a/cyberdrop_dl/utils/next_js.py b/cyberdrop_dl/utils/next_js.pyindex e9d98ab7b..9d0dc7088 100644--- a/cyberdrop_dl/utils/next_js.py+++ b/cyberdrop_dl/utils/next_js.py@@ -94,36 +94,39 @@ def _get_flight_chunks(soup: BeautifulSoup) -> Generator[tuple[FlightDataType, syield data_type, data-def _parse_chunks(flight_data: str) -> Generator[FlightChunk]:+def _parse_chunks(flight_data: str) -> Generator[FlightChunk]: # noqa: C901chunks: dict[ChunkID, FlightChunk] = {}+ def revive_str(value: str) -> Any: # noqa: PLR0911+ if value[0] != "$":+ return value++ if value == "$":+ return ""++ match value[1]:+ case "$":+ return value[2:]+ case "@" | "L":+ chunk_id = value[2:]+ return revive(chunks[chunk_id])+ case "u":+ return None+ case "D":+ return value[2:]+ case "n":+ return int(value[2:])+ case _:+ return value[1:]+def revive(value: Any) -> Any:if not value:return valueif isinstance(value, str):- if value[0] != "$":- return value-- if value == "$":- return ""-- match value[1]:- case "$":- return value[2:]- case "@" | "L":- chunk_id = value[2:]- return revive(chunks[chunk_id])- case "u":- return None- case "D":- return value[2:]- case "n":- return int(value[2:])- case _:- return value[1:]-- elif isinstance(value, list):+ return revive_str(value)++ if isinstance(value, list):for idx, obj in enumerate(value):value[idx] = revive(obj)diff --git a/cyberdrop_dl/utils/nuxt.py b/cyberdrop_dl/utils/nuxt.pyindex 5635712b7..54cdf7882 100644--- a/cyberdrop_dl/utils/nuxt.py+++ b/cyberdrop_dl/utils/nuxt.py@@ -40,19 +40,20 @@ def ifind(nuxt_data: list[Any], attribute: str, *attributes: str) -> Generator[dobjects = (obj for obj in nuxt_data if isinstance(obj, dict) and all(key in obj for key in attributes))for obj in objects:try:- index: int = obj[attribute]- index_map: dict[str, int] = nuxt_data[index]- if not isinstance(index_map, dict):- raise TypeError+ index_map: dict[str, int] = nuxt_data[obj[attribute]]- except (LookupError, TypeError):+ except LookupError:index_map = obj+ else:+ if type(index_map) is not dict:+ index_map = obj+yield _parse_obj(nuxt_data, index_map)def _parse_obj(nuxt_data: list[Any], index_map: dict[str, int]) -> dict[str, Any]:- def hydrate(value: Any) -> Any:+ def hydrate(value: Any) -> Any: # noqa: PLR0911if isinstance(value, list):match value:case ["BigInt", val]:diff --git a/cyberdrop_dl/utils/webdav.py b/cyberdrop_dl/utils/webdav.pyindex 743d81058..a53052f67 100644--- a/cyberdrop_dl/utils/webdav.py+++ b/cyberdrop_dl/utils/webdav.py@@ -61,7 +61,7 @@ class Resource:def parse_propfind(xml_resp: str) -> Generator[Resource]:- root = ET.fromstring(xml_resp)+ root = ET.fromstring(xml_resp) # noqa: S314for response in root.iterfind(".//{DAV:}response"):href = response.find("{DAV:}href")@@ -115,7 +115,7 @@ def create_propfind_xml(def update_tags_from_ns(root: ET.Element[str]) -> ET.Element[str]:- return ET.fromstring(xml_to_bytes(root))+ return ET.fromstring(xml_to_bytes(root)) # noqa: S314def xml_to_bytes(root: ET.Element[str]) -> bytes:diff --git a/pyproject.toml b/pyproject.tomlindex dfaea4fca..a42eb35be 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -137,9 +137,9 @@ extend-safe-fixes = ["TC" # move import from and to TYPE_CHECKING blocks]ignore = [- "ANN401", # any-type+ "ANN", # flake8-annotations"COM812", # missing-trailing-comma- "D", # Documantation+ "D", # Documentation"E501", # suppress line-too-long, let formatter decide"EM", # flake8-errmsg"FIX002", # line-contains-todo@@ -148,9 +148,11 @@ ignore = ["N806", # uppercase variables in functions"PLC0415", # import-outside-top-level"PLR2004", # magic-value-comparison+ "PLW2901", # redefined-loop-name"RET503", # implicit-return"S101", # assert"S110", # try-except-pass+ "S311", # suspicious-non-cryptographic-random-usage"S603", # subprocess-without-shell-equals-true"S607", # start-process-with-partial-path"SIM105", # suppressible-exception@@ -160,6 +162,9 @@ ignore = ["TRY400" # error-instead-of-exception]+[tool.ruff.lint.flake8-boolean-trap]+extend-allowed-calls = ["cyberdrop_dl.logs._enter_context"]+[tool.ruff.lint.flake8-tidy-imports.banned-api]"typing.override".msg = "Use typing_extensions.override instead."diff --git a/scripts/tools/filter_logs.py b/scripts/tools/filter_logs.pyindex c50283f80..d8f4c7716 100644--- a/scripts/tools/filter_logs.py+++ b/scripts/tools/filter_logs.py@@ -1,14 +1,14 @@# /// script# requires-python = ">=3.11"# dependencies = [-# "alive-progress",+# "rich",# ]# ///import argparsefrom collections.abc import Iterablefrom pathlib import Path-from alive_progress import alive_it # type: ignore+from rich.progress import trackLEVELS_TO_INCLUDE = {"WARNING", "ERROR", "CRITICAL"}@@ -19,7 +19,8 @@ def filter_log_file(log_file: Path) -> Iterable[str]:print(f"Filtering: {log_file.resolve()}")log_content = log_file.read_text(encoding="utf8")last_level = None- for line in alive_it(log_content.splitlines()):+ lines = log_content.splitlines()+ for line in track(lines, total=len(lines)):level = line[LEVEL_AT : LEVEL_AT + 9].strip()if level:last_level = leveldiff --git a/tests/conftest.py b/tests/conftest.pyindex 0d2361d81..76a553c0c 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -11,9 +11,6 @@ if TYPE_CHECKING:from collections.abc import AsyncGenerator, Generatorfrom pathlib import Path- class Config(pytest.Config): # type: ignore- test_crawlers_domains: set[str]-def pytest_addoption(parser: pytest.Parser) -> None:parser.addoption(@@ -24,13 +21,13 @@ def pytest_addoption(parser: pytest.Parser) -> None:)-def pytest_configure(config: Config) -> None:+def pytest_configure(config: pytest.Config) -> None:config.test_crawlers_domains = {domain for item in config.getoption("--test-crawlers").split(",") if (domain := item.strip())}-def pytest_collection_modifyitems(config: Config, items: list[pytest.Item]) -> None:+def pytest_collection_modifyitems(config: pytest.Config, items: list[pytest.Item]) -> None:"""When running with --test-crawlers, disable all other tests"""if not config.test_crawlers_domains:returndiff --git a/tests/crawlers/test_xenforo.py b/tests/crawlers/test_xenforo.pyindex 44e54c1c6..a1435972a 100644--- a/tests/crawlers/test_xenforo.py+++ b/tests/crawlers/test_xenforo.py@@ -16,7 +16,7 @@ def _item(url: str) -> ScrapeItem:manager = Manager()-scrape_item = _item("https://xenforo.com/community") # type: ignore+scrape_item = _item("https://xenforo.com/community")crawler_instances = {crawler: crawler(manager) for crawler in crawlers.XF_CRAWLERS}TEST_CRAWLER = crawler_instances[crawlers.CelebForumCrawler]@@ -644,7 +644,7 @@ def test_get_post_title_should_strip_new_lines() -> None:def test_is_attachment_should_handle_none() -> None:- assert TEST_CRAWLER.is_attachment(None) is False # type: ignore+ assert TEST_CRAWLER.is_attachment(None) is False # pyright: ignore[reportArgumentType]@pytest.mark.parametrize(diff --git a/tests/test_cookies.py b/tests/test_cookies.pyindex a114370e7..b5ad42764 100644--- a/tests/test_cookies.py+++ b/tests/test_cookies.py@@ -12,7 +12,7 @@ if TYPE_CHECKING:now = 1_000_000-def make_cookie(+def make_cookie( # noqa: PLR0913*,domain: str,name: str,diff --git a/tests/test_tracebacks.py b/tests/test_tracebacks.pyindex 1647aad4f..382b54ced 100644--- a/tests/test_tracebacks.py+++ b/tests/test_tracebacks.py@@ -24,7 +24,7 @@ def test_bs4_are_truncated_on_tracebacks() -> None:local_soup = soupwith Console(record=True, width=None, file=NULL_FILE) as console:try:- raise ValueError+ raise ValueError # noqa: TRY301except ValueError:traceback = Traceback(show_locals=True)