Skip to content

Bulk asynchronous downloader for multiple file hosts

refactor: ruff manual fixes

NTFSvolumec391751c2a0b
diff --git a/cyberdrop_dl/clients/download_client.py b/cyberdrop_dl/clients/download_client.py
index 66ed0ee6e..268893690 100644
--- a/cyberdrop_dl/clients/download_client.py
+++ b/cyberdrop_dl/clients/download_client.py
@@ -7,7 +7,7 @@ import os
from functools import partial, wraps
from http import HTTPStatus
from pathlib import Path
-from typing import TYPE_CHECKING, List, Tuple
+from typing import TYPE_CHECKING
import aiofiles
import aiohttp
@@ -338,7 +338,7 @@ class DownloadClient:
media_item.download_filename = media_item.complete_file.name
return proceed, skip
- async def iterate_filename(self, complete_file: Path, media_item: MediaItem) -> Tuple[Path, Path]:
+ async def iterate_filename(self, complete_file: Path, media_item: MediaItem) -> tuple[Path, Path]:
"""Iterates the filename until it is unique"""
partial_file = None
for iteration in itertools.count(1):
@@ -390,7 +390,7 @@ class DownloadClient:
return True
@property
- def file_path(self) -> List[str]:
+ def file_path(self) -> list[str]:
return self._file_path
@file_path.setter
diff --git a/cyberdrop_dl/clients/hash_client.py b/cyberdrop_dl/clients/hash_client.py
index b2bccd3d2..a7897550a 100644
--- a/cyberdrop_dl/clients/hash_client.py
+++ b/cyberdrop_dl/clients/hash_client.py
@@ -95,12 +95,10 @@ class HashClient:
other_files = data["others"]
# Get all matches from the database
- all_matches = list(
- map(
- lambda x: pathlib.Path(x[0], x[1]),
- await self.manager.db_manager.hash_table.get_files_with_hash_matches(hash, size),
- )
- )
+ all_matches = [
+ pathlib.Path(x[0], x[1])
+ for x in await self.manager.db_manager.hash_table.get_files_with_hash_matches(hash, size)
+ ]
# Filter out files with the same path as any file in other_files
other_matches = [match for match in all_matches if str(match) not in other_files]
@@ -177,7 +175,7 @@ class HashClient:
if selected_file:
size_dict[size] = {
"selected": selected_file,
- "others": list(map(lambda x: str(x.absolute()), files)),
+ "others": [str(x.absolute()) for x in files],
}
else:
del size_dict[size]
diff --git a/cyberdrop_dl/clients/scraper_client.py b/cyberdrop_dl/clients/scraper_client.py
index 2b9886d36..bc0067cb8 100644
--- a/cyberdrop_dl/clients/scraper_client.py
+++ b/cyberdrop_dl/clients/scraper_client.py
@@ -3,7 +3,7 @@ from __future__ import annotations
import json
import os
from functools import wraps
-from typing import TYPE_CHECKING, Dict, Optional
+from typing import TYPE_CHECKING, Dict
import aiohttp
from aiohttp import ClientSession
@@ -78,7 +78,7 @@ class ScraperClient:
domain: str,
url: URL,
client_session: ClientSession,
- origin: Optional[ScrapeItem | URL] = None,
+ origin: ScrapeItem | URL | None = None,
with_response_url: bool = False,
) -> str:
"""Returns the resolved URL from the given URL"""
@@ -112,7 +112,7 @@ class ScraperClient:
domain: str,
url: URL,
client_session: ClientSession,
- origin: Optional[ScrapeItem | URL] = None,
+ origin: ScrapeItem | URL | None = None,
with_response_url: bool = False,
) -> BeautifulSoup:
"""Returns a BeautifulSoup object from the given URL"""
@@ -137,7 +137,7 @@ class ScraperClient:
return BeautifulSoup(text, "html.parser")
async def get_BS4_and_return_URL(
- self, domain: str, url: URL, origin: Optional[ScrapeItem | URL] = None
+ self, domain: str, url: URL, origin: ScrapeItem | URL | None = None
) -> tuple[BeautifulSoup, URL]:
"""Returns a BeautifulSoup object and response URL from the given URL"""
return await self.get_BS4(domain, url, origin=origin, with_response_url=True)
@@ -147,10 +147,10 @@ class ScraperClient:
self,
domain: str,
url: URL,
- params: Optional[Dict] = None,
- headers_inc: Optional[Dict] = None,
+ params: dict | None = None,
+ headers_inc: dict | None = None,
client_session: ClientSession = None,
- origin: Optional[ScrapeItem | URL] = None,
+ origin: ScrapeItem | URL | None = None,
) -> Dict:
"""Returns a JSON object from the given URL"""
headers = {**self._headers, **headers_inc} if headers_inc else self._headers
@@ -167,7 +167,7 @@ class ScraperClient:
@limiter
async def get_text(
- self, domain: str, url: URL, client_session: ClientSession, origin: Optional[ScrapeItem | URL] = None
+ self, domain: str, url: URL, client_session: ClientSession, origin: ScrapeItem | URL | None = None
) -> str:
"""Returns a text object from the given URL"""
async with client_session.get(
@@ -187,11 +187,11 @@ class ScraperClient:
domain: str,
url: URL,
client_session: ClientSession,
- data: Dict,
+ data: dict,
req_resp: bool = True,
- raw: Optional[bool] = False,
- origin: Optional[ScrapeItem | URL] = None,
- ) -> Dict:
+ raw: bool = False,
+ origin: ScrapeItem | URL | None = None,
+ ) -> dict:
"""Returns a JSON object from the given URL when posting data. If raw == True, returns raw binary data of response"""
async with client_session.post(
url, headers=self._headers, ssl=self.client_manager.ssl_context, proxy=self.client_manager.proxy, data=data
diff --git a/cyberdrop_dl/managers/cache_manager.py b/cyberdrop_dl/managers/cache_manager.py
index be3122602..37c73753f 100644
--- a/cyberdrop_dl/managers/cache_manager.py
+++ b/cyberdrop_dl/managers/cache_manager.py
@@ -2,7 +2,7 @@ from __future__ import annotations
from dataclasses import field
from pathlib import Path
-from typing import TYPE_CHECKING, Any, Dict
+from typing import TYPE_CHECKING, Any
import yaml
@@ -10,14 +10,14 @@ if TYPE_CHECKING:
from cyberdrop_dl.managers.manager import Manager
-def _save_yaml(file: Path, data: Dict) -> None:
+def _save_yaml(file: Path, data: dict) -> None:
"""Saves a dict to a yaml file"""
file.parent.mkdir(parents=True, exist_ok=True)
with open(file, "w") as yaml_file:
yaml.dump(data, yaml_file)
-def _load_yaml(file: Path) -> Dict:
+def _load_yaml(file: Path) -> dict:
"""Loads a yaml file and returns it as a dict"""
with open(file) as yaml_file:
return yaml.load(yaml_file.read(), Loader=yaml.FullLoader)
diff --git a/cyberdrop_dl/managers/client_manager.py b/cyberdrop_dl/managers/client_manager.py
index f6a81a32d..1aa29fda1 100644
--- a/cyberdrop_dl/managers/client_manager.py
+++ b/cyberdrop_dl/managers/client_manager.py
@@ -3,7 +3,7 @@ from __future__ import annotations
import asyncio
import ssl
from http import HTTPStatus
-from typing import TYPE_CHECKING, Optional
+from typing import TYPE_CHECKING
import aiohttp
import certifi
@@ -106,7 +106,7 @@ class ClientManager:
@staticmethod
async def check_http_status(
- response: ClientResponse, download: bool = False, origin: Optional[ScrapeItem | URL] = None
+ response: ClientResponse, download: bool = False, origin: ScrapeItem | URL | None = None
) -> None:
"""Checks the HTTP status code and raises an exception if it's not acceptable"""
status = response.status
@@ -119,7 +119,7 @@ class ClientManager:
if HTTPStatus.OK <= status < HTTPStatus.BAD_REQUEST:
return
- if any({domain in response.url.host.lower() for domain in ("gofile", "imgur")}):
+ if any(domain in response.url.host for domain in ("gofile", "imgur")):
try:
JSON_Resp: dict = await response.json()
if "status" in JSON_Resp:
diff --git a/cyberdrop_dl/managers/config_manager.py b/cyberdrop_dl/managers/config_manager.py
index 8c7424d56..5193a4f3e 100644
--- a/cyberdrop_dl/managers/config_manager.py
+++ b/cyberdrop_dl/managers/config_manager.py
@@ -15,7 +15,7 @@ if TYPE_CHECKING:
from cyberdrop_dl.managers.manager import Manager
-def _match_config_dicts(default: Dict, existing: Dict) -> Dict:
+def _match_config_dicts(default: dict, existing: dict) -> Dict:
"""Matches the keys of two dicts and returns the default dict with the values of the existing dict"""
for group in default:
for key in default[group]:
@@ -24,7 +24,7 @@ def _match_config_dicts(default: Dict, existing: Dict) -> Dict:
return default
-def _save_yaml(file: Path, data: Dict) -> None:
+def _save_yaml(file: Path, data: dict) -> None:
"""Saves a dict to a yaml file"""
file.parent.mkdir(parents=True, exist_ok=True)
with open(file, "w") as yaml_file:
@@ -60,9 +60,9 @@ class ConfigManager:
self.settings: Path = field(init=False)
self.global_settings: Path = field(init=False)
- self.authentication_data: Dict = field(init=False)
- self.settings_data: Dict = field(init=False)
- self.global_settings_data: Dict = field(init=False)
+ self.authentication_data: dict = field(init=False)
+ self.settings_data: dict = field(init=False)
+ self.global_settings_data: dict = field(init=False)
def startup(self) -> None:
"""Pre-startup process for the config manager"""
@@ -257,7 +257,7 @@ class ConfigManager:
"""~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"""
@staticmethod
- def create_new_config(new_settings: Path, settings_data: Dict) -> None:
+ def create_new_config(new_settings: Path, settings_data: dict) -> None:
"""Creates a new settings config file"""
settings_data["Files"]["input_file"] = str(settings_data["Files"]["input_file"])
settings_data["Files"]["download_folder"] = str(settings_data["Files"]["download_folder"])
diff --git a/cyberdrop_dl/managers/download_manager.py b/cyberdrop_dl/managers/download_manager.py
index 678f37ee9..343186e53 100644
--- a/cyberdrop_dl/managers/download_manager.py
+++ b/cyberdrop_dl/managers/download_manager.py
@@ -10,8 +10,6 @@ from typing import TYPE_CHECKING
from cyberdrop_dl.utils.utilities import FILE_FORMATS, log_debug
if TYPE_CHECKING:
- from typing import Dict
-
from cyberdrop_dl.managers.manager import Manager
from cyberdrop_dl.utils.dataclasses.url_objects import MediaItem
@@ -45,7 +43,7 @@ class FileLock:
class DownloadManager:
def __init__(self, manager: Manager):
self.manager = manager
- self._download_instances: Dict = {}
+ self._download_instances: dict = {}
self.file_lock = FileLock()
diff --git a/cyberdrop_dl/managers/log_manager.py b/cyberdrop_dl/managers/log_manager.py
index 9914cc61d..c4ead72d8 100644
--- a/cyberdrop_dl/managers/log_manager.py
+++ b/cyberdrop_dl/managers/log_manager.py
@@ -2,7 +2,7 @@ from __future__ import annotations
import csv
from pathlib import Path
-from typing import TYPE_CHECKING, Optional
+from typing import TYPE_CHECKING
import aiofiles
@@ -47,15 +47,15 @@ class LogManager:
"""Writes to the last post log"""
await self.write_to_csv(self.last_post_log, url=url)
- async def write_unsupported_urls_log(self, url: URL, origin: Optional[URL] = None) -> None:
+ async def write_unsupported_urls_log(self, url: URL, origin: URL | None = None) -> None:
"""Writes to the unsupported urls log"""
await self.write_to_csv(self.unsupported_urls_log, url=url, origin=origin)
- async def write_download_error_log(self, url: URL, error_message: str, origin: Optional[URL] = None) -> None:
+ async def write_download_error_log(self, url: URL, error_message: str, origin: URL | None = None) -> None:
"""Writes to the download error log"""
await self.write_to_csv(self.download_error_log, url=url, error=error_message, origin=origin)
- async def write_scrape_error_log(self, url: URL, error_message: str, origin: Optional[URL] = None) -> None:
+ async def write_scrape_error_log(self, url: URL, error_message: str, origin: URL | None = None) -> None:
"""Writes to the scrape error log"""
await self.write_to_csv(self.scrape_error_log, url=url, error=error_message, origin=origin)
diff --git a/cyberdrop_dl/managers/manager.py b/cyberdrop_dl/managers/manager.py
index e82d7f147..f95b2de30 100644
--- a/cyberdrop_dl/managers/manager.py
+++ b/cyberdrop_dl/managers/manager.py
@@ -76,7 +76,7 @@ class Manager:
# Adjust settings for SimpCity update
simp_settings_adjusted = self.cache_manager.get("simp_settings_adjusted")
- if simp_settings_adjusted == None:
+ if not simp_settings_adjusted:
for config in self.config_manager.get_configs():
if config != self.config_manager.loaded_config:
self.config_manager.change_config(config)
@@ -167,7 +167,7 @@ class Manager:
forum_credentials_provided = {}
auth_data_forums = self.config_manager.authentication_data["Forums"]
- auth_data_others = self.config_manager.authentication_data.copy()
+ auth_data_others: dict[str, dict] = self.config_manager.authentication_data.copy()
auth_data_others.pop("Forums", None)
for forum in SupportedDomains.supported_forums_map.values():
@@ -182,7 +182,7 @@ class Manager:
}
for site, auth_entries in auth_data_others.items():
- auth_provided[site] = all([value for value in auth_entries.values()])
+ auth_provided[site] = all(auth_entries.values())
print_settings = copy.deepcopy(self.config_manager.settings_data)
print_settings["Files"]["input_file"] = str(print_settings["Files"]["input_file"])
diff --git a/cyberdrop_dl/scraper/crawler.py b/cyberdrop_dl/scraper/crawler.py
index 051fa55c0..eaf443914 100644
--- a/cyberdrop_dl/scraper/crawler.py
+++ b/cyberdrop_dl/scraper/crawler.py
@@ -4,7 +4,7 @@ import asyncio
import copy
from abc import ABC, abstractmethod
from dataclasses import field
-from typing import TYPE_CHECKING, Any, Optional, Tuple, Union
+from typing import TYPE_CHECKING, Any
from bs4 import BeautifulSoup
from yarl import URL
@@ -72,8 +72,8 @@ class Crawler(ABC):
scrape_item: ScrapeItem,
filename: str,
ext: str,
- custom_filename: Optional[str] = None,
- debrid_link: Optional[URL] = None,
+ custom_filename: str | None = None,
+ debrid_link: URL | None = None,
) -> None:
"""Finishes handling the file and hands it off to the downloader"""
if custom_filename:
@@ -114,7 +114,7 @@ class Crawler(ABC):
"""~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"""
- async def check_post_number(self, post_number: int, current_post_number: int) -> Tuple[bool, bool]:
+ async def check_post_number(self, post_number: int, current_post_number: int) -> tuple[bool, bool]:
"""Checks if the program should scrape the current post"""
"""Returns (scrape_post, continue_scraping)"""
scrape_single_forum_post = self.manager.config_manager.settings_data["Download_Options"][
@@ -215,9 +215,9 @@ class Crawler(ABC):
url: URL,
new_title_part: str,
part_of_album: bool = False,
- album_id: Union[str, None] = None,
- possible_datetime: Optional[int] = None,
- add_parent: Optional[URL] = None,
+ album_id: str | None = None,
+ possible_datetime: int | None = None,
+ add_parent: URL | None = None,
) -> ScrapeItem:
"""Creates a scrape item"""
scrape_item = copy.deepcopy(parent_scrape_item)
@@ -233,7 +233,7 @@ class Crawler(ABC):
scrape_item.album_id = album_id
return scrape_item
- async def create_title(self, title: str, album_id: Optional[str], thread_id: Optional[str]) -> str:
+ async def create_title(self, title: str, album_id: str | None, thread_id: str | None) -> str:
"""Creates the title for the scrape item"""
if not title:
title = "Untitled"
diff --git a/cyberdrop_dl/scraper/crawlers/coomer_crawler.py b/cyberdrop_dl/scraper/crawlers/coomer_crawler.py
index 4902cd2e1..d35d2fced 100644
--- a/cyberdrop_dl/scraper/crawlers/coomer_crawler.py
+++ b/cyberdrop_dl/scraper/crawlers/coomer_crawler.py
@@ -2,7 +2,7 @@ from __future__ import annotations
import calendar
import datetime
-from typing import TYPE_CHECKING, Dict, Optional, Tuple
+from typing import TYPE_CHECKING
from aiolimiter import AsyncLimiter
from yarl import URL
@@ -66,7 +66,6 @@ class CoomerCrawler(Crawler):
self.client.client_manager.cookies.update_cookies({"session": ""}, response_url=self.primary_base_domain)
for user in JSON_Resp:
id = user["id"]
- name = user["name"]
service = user["service"]
url = self.primary_base_domain / service / "user" / id
new_scrape_item = await self.create_scrape_item(scrape_item, url, None, True, None, None)
@@ -116,7 +115,7 @@ class CoomerCrawler(Crawler):
await self.handle_post_content(scrape_item, post, user, user_str)
@error_handling_wrapper
- async def handle_post_content(self, scrape_item: ScrapeItem, post: Dict, user: str, user_str: str) -> None:
+ async def handle_post_content(self, scrape_item: ScrapeItem, post: dict, user: str, user_str: str) -> None:
"""Handles the content of a post"""
if (
"#ad" in post["content"]
@@ -190,7 +189,7 @@ class CoomerCrawler(Crawler):
title: str,
post_id: str,
date: str,
- add_parent: Optional[URL] = None,
+ add_parent: URL | None = None,
) -> None:
"""Creates a new scrape item with the same parent as the old scrape item"""
post_title = None
@@ -221,14 +220,14 @@ class CoomerCrawler(Crawler):
return user
@staticmethod
- async def get_service_and_user(scrape_item: ScrapeItem) -> Tuple[str, str]:
+ async def get_service_and_user(scrape_item: ScrapeItem) -> tuple[str, str]:
"""Gets the service and user from a scrape item"""
user = scrape_item.url.parts[3]
service = scrape_item.url.parts[1]
return service, user
@staticmethod
- async def get_service_user_and_post(scrape_item: ScrapeItem) -> Tuple[str, str, str]:
+ async def get_service_user_and_post(scrape_item: ScrapeItem) -> tuple[str, str, str]:
"""Gets the service, user and post id from a scrape item"""
user = scrape_item.url.parts[3]
service = scrape_item.url.parts[1]
diff --git a/cyberdrop_dl/scraper/crawlers/cyberdrop_crawler.py b/cyberdrop_dl/scraper/crawlers/cyberdrop_crawler.py
index 601e29894..edfe9be5e 100644
--- a/cyberdrop_dl/scraper/crawlers/cyberdrop_crawler.py
+++ b/cyberdrop_dl/scraper/crawlers/cyberdrop_crawler.py
@@ -119,7 +119,7 @@ class CyberdropCrawler(Crawler):
"""
- if any([part in url.parts for part in ("a", "f")]):
+ if any(part in url.parts for part in ("a", "f")):
return url
if self.is_cdn(url):
diff --git a/cyberdrop_dl/scraper/crawlers/cyberfile_crawler.py b/cyberdrop_dl/scraper/crawlers/cyberfile_crawler.py
index c1a0e4771..db9e911ce 100644
--- a/cyberdrop_dl/scraper/crawlers/cyberfile_crawler.py
+++ b/cyberdrop_dl/scraper/crawlers/cyberfile_crawler.py
@@ -230,9 +230,9 @@ class CyberfileCrawler(Crawler):
return
@error_handling_wrapper
- async def handle_content_id(self, scrape_item: ScrapeItem, contentId: int) -> None:
+ async def handle_content_id(self, scrape_item: ScrapeItem, content_id: int) -> None:
"""Scrapes a file using the content id"""
- data = {"u": contentId}
+ data = {"u": content_id}
async with self.request_limiter:
ajax_dict = await self.client.post_data(self.domain, self.api_details, data=data, origin=scrape_item)
ajax_soup = BeautifulSoup(ajax_dict["html"].replace("\\", ""), "html.parser")
diff --git a/cyberdrop_dl/scraper/crawlers/f95zone_crawler.py b/cyberdrop_dl/scraper/crawlers/f95zone_crawler.py
index 6a8e800fb..9982a42e8 100644
--- a/cyberdrop_dl/scraper/crawlers/f95zone_crawler.py
+++ b/cyberdrop_dl/scraper/crawlers/f95zone_crawler.py
@@ -1,6 +1,6 @@
from __future__ import annotations
-from typing import TYPE_CHECKING, Optional
+from typing import TYPE_CHECKING
from aiolimiter import AsyncLimiter
from bs4 import Tag
@@ -355,7 +355,7 @@ class F95ZoneCrawler(Crawler):
await self.handle_file(link, new_scrape_item, filename, ext)
@error_handling_wrapper
- async def handle_link_confirmation(self, link: URL) -> Optional[URL]:
+ async def handle_link_confirmation(self, link: URL) -> URL | None:
"""Handles link confirmation"""
async with self.request_limiter:
await self.client.get_BS4(self.domain, link)
diff --git a/cyberdrop_dl/scraper/crawlers/kemono_crawler.py b/cyberdrop_dl/scraper/crawlers/kemono_crawler.py
index 465b430b2..5ba98da93 100644
--- a/cyberdrop_dl/scraper/crawlers/kemono_crawler.py
+++ b/cyberdrop_dl/scraper/crawlers/kemono_crawler.py
@@ -3,7 +3,7 @@ from __future__ import annotations
import calendar
import datetime
import re
-from typing import TYPE_CHECKING, Dict, Optional, Tuple
+from typing import TYPE_CHECKING
from aiolimiter import AsyncLimiter
from yarl import URL
@@ -123,7 +123,7 @@ class KemonoCrawler(Crawler):
await self.handle_post_content(scrape_item, post, user, user_str)
@error_handling_wrapper
- async def handle_post_content(self, scrape_item: ScrapeItem, post: Dict, user: str, user_str: str) -> None:
+ async def handle_post_content(self, scrape_item: ScrapeItem, post: dict, user: str, user_str: str) -> None:
"""Handles the content of a post"""
scrape_item.type = FILE_HOST_ALBUM
@@ -167,7 +167,7 @@ class KemonoCrawler(Crawler):
await handle_file(file)
scrape_item.children += 1
- async def get_content_links(self, scrape_item: ScrapeItem, post: Dict, user: str) -> None:
+ async def get_content_links(self, scrape_item: ScrapeItem, post: dict, user: str) -> None:
"""Gets links out of content in post"""
content = post.get("content", "")
if not content:
@@ -239,7 +239,7 @@ class KemonoCrawler(Crawler):
title: str,
post_id: str,
date: str,
- add_parent: Optional[URL] = None,
+ add_parent: URL | None = None,
) -> None:
"""Creates a new scrape item with the same parent as the old scrape item"""
post_title = None
@@ -272,14 +272,14 @@ class KemonoCrawler(Crawler):
return user
@staticmethod
- async def get_service_and_user(scrape_item: ScrapeItem) -> Tuple[str, str]:
+ async def get_service_and_user(scrape_item: ScrapeItem) -> tuple[str, str]:
"""Gets the service and user from a scrape item"""
user = scrape_item.url.parts[3]
service = scrape_item.url.parts[1]
return service, user
@staticmethod
- async def get_service_user_and_post(scrape_item: ScrapeItem) -> Tuple[str, str, str]:
+ async def get_service_user_and_post(scrape_item: ScrapeItem) -> tuple[str, str, str]:
"""Gets the service, user and post id from a scrape item"""
user = scrape_item.url.parts[3]
service = scrape_item.url.parts[1]
diff --git a/cyberdrop_dl/scraper/crawlers/nekohouse_crawler.py b/cyberdrop_dl/scraper/crawlers/nekohouse_crawler.py
index a9946f2fb..30c2c98ce 100644
--- a/cyberdrop_dl/scraper/crawlers/nekohouse_crawler.py
+++ b/cyberdrop_dl/scraper/crawlers/nekohouse_crawler.py
@@ -2,7 +2,7 @@ from __future__ import annotations
import calendar
import datetime
-from typing import TYPE_CHECKING, Dict, Optional, Tuple
+from typing import TYPE_CHECKING
from aiolimiter import AsyncLimiter
from bs4 import BeautifulSoup
@@ -208,7 +208,7 @@ class NekohouseCrawler(Crawler):
await self.handle_post_content(scrape_item, data, user, user_str)
@error_handling_wrapper
- async def handle_post_content(self, scrape_item: ScrapeItem, post: Dict, user: str, user_str: str) -> None:
+ async def handle_post_content(self, scrape_item: ScrapeItem, post: dict, user: str, user_str: str) -> None:
"""Handles the content of a post"""
date = post["published"].replace("T", " ")
post_id = post["id"]
@@ -244,7 +244,7 @@ class NekohouseCrawler(Crawler):
title: str,
post_id: str,
date: str,
- add_parent: Optional[URL] = None,
+ add_parent: URL | None = None,
) -> None:
"""Creates a new scrape item with the same parent as the old scrape item"""
post_title = None
@@ -301,14 +301,14 @@ class NekohouseCrawler(Crawler):
return user
@staticmethod
- async def get_service_and_user(scrape_item: ScrapeItem) -> Tuple[str, str]:
+ async def get_service_and_user(scrape_item: ScrapeItem) -> tuple[str, str]:
"""Gets the service and user from a scrape item"""
user = scrape_item.url.parts[3]
service = scrape_item.url.parts[1]
return service, user
@staticmethod
- async def get_service_user_and_post(scrape_item: ScrapeItem) -> Tuple[str, str, str]:
+ async def get_service_user_and_post(scrape_item: ScrapeItem) -> tuple[str, str, str]:
"""Gets the service, user and post id from a scrape item"""
user = scrape_item.url.parts[3]
service = scrape_item.url.parts[1]
diff --git a/cyberdrop_dl/scraper/crawlers/realdebrid_crawler.py b/cyberdrop_dl/scraper/crawlers/realdebrid_crawler.py
index 4ab969aaa..cca1572d9 100644
--- a/cyberdrop_dl/scraper/crawlers/realdebrid_crawler.py
+++ b/cyberdrop_dl/scraper/crawlers/realdebrid_crawler.py
@@ -93,7 +93,7 @@ class RealDebridCrawler(Crawler):
await self.handle_file(database_url, scrape_item, filename, ext, debrid_link=debrid_url)
async def is_self_hosted(self, url: URL):
- return any({subdomain in url.host for subdomain in ("download.", "my.")}) and self.domain in url.host
+ return any(subdomain in url.host for subdomain in ("download.", "my.")) and self.domain in url.host
async def get_original_url(self, scrape_item: ScrapeItem) -> URL:
if await self.is_self_hosted(scrape_item.url):
diff --git a/cyberdrop_dl/scraper/crawlers/reddit_crawler.py b/cyberdrop_dl/scraper/crawlers/reddit_crawler.py
index 7381039ec..108bc3abb 100644
--- a/cyberdrop_dl/scraper/crawlers/reddit_crawler.py
+++ b/cyberdrop_dl/scraper/crawlers/reddit_crawler.py
@@ -1,6 +1,6 @@
from __future__ import annotations
-from typing import TYPE_CHECKING, Optional
+from typing import TYPE_CHECKING
import aiohttp
import asyncpraw
@@ -190,7 +190,7 @@ class RedditCrawler(Crawler):
"""~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"""
async def create_new_scrape_item(
- self, link: URL, old_scrape_item: ScrapeItem, title: str, date: int, add_parent: Optional[URL] = None
+ self, link: URL, old_scrape_item: ScrapeItem, title: str, date: int, add_parent: URL | None = None
) -> ScrapeItem:
"""Creates a new scrape item with the same parent as the old scrape item"""
diff --git a/cyberdrop_dl/scraper/crawlers/simpcity_crawler.py b/cyberdrop_dl/scraper/crawlers/simpcity_crawler.py
index 8297ec642..5d23e705e 100644
--- a/cyberdrop_dl/scraper/crawlers/simpcity_crawler.py
+++ b/cyberdrop_dl/scraper/crawlers/simpcity_crawler.py
@@ -122,7 +122,7 @@ class SimpCityCrawler(Crawler):
if scrape_post:
try:
date = int(post.select_one(self.post_date_selector).get(self.post_date_attribute))
- except:
+ except AttributeError:
pass
new_scrape_item = await self.create_scrape_item(
scrape_item,
diff --git a/cyberdrop_dl/scraper/crawlers/socialmediagirls_crawler.py b/cyberdrop_dl/scraper/crawlers/socialmediagirls_crawler.py
index 4407aa980..4e17f46a8 100644
--- a/cyberdrop_dl/scraper/crawlers/socialmediagirls_crawler.py
+++ b/cyberdrop_dl/scraper/crawlers/socialmediagirls_crawler.py
@@ -1,7 +1,7 @@
from __future__ import annotations
import re
-from typing import TYPE_CHECKING, Optional
+from typing import TYPE_CHECKING
from aiolimiter import AsyncLimiter
from bs4 import Tag
@@ -373,7 +373,7 @@ class SocialMediaGirlsCrawler(Crawler):
await self.handle_file(link, new_scrape_item, filename, ext)
@error_handling_wrapper
- async def handle_link_confirmation(self, link: URL) -> Optional[URL]:
+ async def handle_link_confirmation(self, link: URL) -> URL | None:
"""Handles link confirmation"""
async with self.request_limiter:
soup: BeautifulSoup = await self.client.get_BS4(self.domain, link)
diff --git a/cyberdrop_dl/scraper/jdownloader.py b/cyberdrop_dl/scraper/jdownloader.py
index 3cc1fc7b2..17998d257 100644
--- a/cyberdrop_dl/scraper/jdownloader.py
+++ b/cyberdrop_dl/scraper/jdownloader.py
@@ -3,7 +3,7 @@ from __future__ import annotations
import time
from dataclasses import field
from pathlib import Path
-from typing import TYPE_CHECKING, Optional
+from typing import TYPE_CHECKING
from myjdapi import myjdapi
@@ -57,7 +57,7 @@ class JDownloader:
time.sleep(20)
async def direct_unsupported_to_jdownloader(
- self, url: URL, title: str, relative_download_folder: Optional[Path] = None
+ self, url: URL, title: str, relative_download_folder: Path | None = None
) -> None:
"""Sends links to JDownloader"""
try:
diff --git a/cyberdrop_dl/scraper/scraper.py b/cyberdrop_dl/scraper/scraper.py
index 54e38a93f..531c20047 100644
--- a/cyberdrop_dl/scraper/scraper.py
+++ b/cyberdrop_dl/scraper/scraper.py
@@ -17,8 +17,6 @@ from cyberdrop_dl.utils.dataclasses.url_objects import MediaItem, ScrapeItem
from cyberdrop_dl.utils.utilities import get_download_path, get_filename_and_ext, log
if TYPE_CHECKING:
- from typing import List
-
from cyberdrop_dl.managers.manager import Manager
from cyberdrop_dl.scraper.crawler import Crawler
@@ -386,7 +384,7 @@ class ScrapeMapper:
"""~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"""
@staticmethod
- async def regex_links(line: str) -> List:
+ async def regex_links(line: str) -> list:
"""Regex grab the links from the URLs.txt file
This allows code blocks or full paragraphs to be copy and pasted into the URLs.txt"""
yarl_links = []
diff --git a/cyberdrop_dl/ui/progress/statistic_progress.py b/cyberdrop_dl/ui/progress/statistic_progress.py
index faea9fafe..eea3266e1 100644
--- a/cyberdrop_dl/ui/progress/statistic_progress.py
+++ b/cyberdrop_dl/ui/progress/statistic_progress.py
@@ -46,7 +46,7 @@ class DownloadStatsProgress:
)
self.progress_group = Group(self.progress)
- self.failure_types: Dict[str, TaskID] = {}
+ self.failure_types: dict[str, TaskID] = {}
self.failed_files = 0
self.unsupported_urls = 0
self.sent_to_jdownloader = 0
@@ -120,7 +120,7 @@ class ScrapeStatsProgress:
)
self.progress_group = Group(self.progress)
- self.failure_types: Dict[str, TaskID] = {}
+ self.failure_types: dict[str, TaskID] = {}
self.failed_files = 0
self.unsupported_urls = 0
self.sent_to_jdownloader = 0
diff --git a/cyberdrop_dl/ui/prompts/general_prompts.py b/cyberdrop_dl/ui/prompts/general_prompts.py
index a72e8d775..bbfa41577 100644
--- a/cyberdrop_dl/ui/prompts/general_prompts.py
+++ b/cyberdrop_dl/ui/prompts/general_prompts.py
@@ -16,8 +16,6 @@ from cyberdrop_dl.utils.transfer.transfer_v4_db import transfer_v4_db
from cyberdrop_dl.utils.utilities import log
if TYPE_CHECKING:
- from typing import List
-
from cyberdrop_dl.managers.manager import Manager
console = Console()
@@ -44,14 +42,14 @@ def main_prompt(manager: Manager) -> int:
]
simp_disclaimer_shown = manager.cache_manager.get("simp_disclaimer_shown")
- if simp_disclaimer_shown == None:
+ if not simp_disclaimer_shown:
choices = [Choice(-1, "!! VIEW DISCLAIMER !!")]
action = inquirer.select(
message="What would you like to do?",
choices=choices,
long_instruction="ARROW KEYS: Navigate | ENTER: Select",
- style=get_style({"pointer": "#ff0000 bold"}) if simp_disclaimer_shown == None else None,
+ style=get_style({"pointer": "#ff0000 bold"}) if not simp_disclaimer_shown else None,
vi_mode=manager.vi_mode,
).execute()
@@ -80,7 +78,7 @@ def manage_configs_prompt(manager: Manager) -> int:
return action
-def select_config_prompt(manager: Manager, configs: List) -> str:
+def select_config_prompt(manager: Manager, configs: list) -> str:
"""Select a config file from a list of configs"""
choice = inquirer.fuzzy(
choices=configs,
diff --git a/cyberdrop_dl/ui/prompts/settings_authentication_prompts.py b/cyberdrop_dl/ui/prompts/settings_authentication_prompts.py
index 7861c3acc..0d6204ff1 100644
--- a/cyberdrop_dl/ui/prompts/settings_authentication_prompts.py
+++ b/cyberdrop_dl/ui/prompts/settings_authentication_prompts.py
@@ -10,8 +10,6 @@ from cyberdrop_dl.managers.manager import Manager
from cyberdrop_dl.utils.args.browser_cookie_extraction import get_forum_cookies
if TYPE_CHECKING:
- from typing import Dict
-
from cyberdrop_dl.managers.manager import Manager
console = Console()
@@ -246,7 +244,7 @@ def edit_forum_authentication_values_prompt(manager: Manager) -> None:
return
-def edit_jdownloader_authentication_values_prompt(auth: Dict) -> None:
+def edit_jdownloader_authentication_values_prompt(auth: dict) -> None:
"""Edit the JDownloader authentication values"""
console.clear()
jdownloader_username = inquirer.text(
@@ -267,7 +265,7 @@ def edit_jdownloader_authentication_values_prompt(auth: Dict) -> None:
auth["JDownloader"]["jdownloader_device"] = jdownloader_device
-def edit_reddit_authentication_values_prompt(auth: Dict) -> None:
+def edit_reddit_authentication_values_prompt(auth: dict) -> None:
"""Edit the reddit authentication values"""
console.clear()
console.print("You can create a Reddit App to use here: https://www.reddit.com/prefs/apps/")
diff --git a/cyberdrop_dl/ui/prompts/settings_user_prompts.py b/cyberdrop_dl/ui/prompts/settings_user_prompts.py
index 4322b5024..e7a076466 100644
--- a/cyberdrop_dl/ui/prompts/settings_user_prompts.py
+++ b/cyberdrop_dl/ui/prompts/settings_user_prompts.py
@@ -11,8 +11,6 @@ from rich.console import Console
from cyberdrop_dl.utils.dataclasses.supported_domains import SupportedDomains
if TYPE_CHECKING:
- from typing import Dict
-
from cyberdrop_dl.managers.manager import Manager
console = Console()
@@ -93,7 +91,7 @@ def edit_config_values_prompt(manager: Manager) -> None:
return
-def edit_download_options_prompt(manager: Manager, config: Dict) -> None:
+def edit_download_options_prompt(manager: Manager, config: dict) -> None:
"""Edit the download options"""
console.clear()
action = inquirer.checkbox(
@@ -161,7 +159,7 @@ def edit_download_options_prompt(manager: Manager, config: Dict) -> None:
config["Download_Options"][key] = True
-def edit_input_output_file_paths_prompt(manager: Manager, config: Dict) -> None:
+def edit_input_output_file_paths_prompt(manager: Manager, config: dict) -> None:
"""Edit the input / output file paths"""
console.clear()
console.print("Editing Input / Output File Paths")
@@ -182,7 +180,7 @@ def edit_input_output_file_paths_prompt(manager: Manager, config: Dict) -> None:
config["Files"]["download_folder"] = Path(download_folder)
-def edit_log_file_naming_path_prompt(manager: Manager, config: Dict) -> None:
+def edit_log_file_naming_path_prompt(manager: Manager, config: dict) -> None:
"""Edit the log file naming / path"""
console.clear()
console.print("Editing Log File Naming / Path")
@@ -237,7 +235,7 @@ def edit_log_file_naming_path_prompt(manager: Manager, config: Dict) -> None:
config["Logs"]["webhook_url"] = webhook_url
-def edit_file_size_limits_prompt(manager: Manager, config: Dict) -> None:
+def edit_file_size_limits_prompt(manager: Manager, config: dict) -> None:
"""Edit the file size limits"""
console.clear()
console.print("Editing File Size Limits")
@@ -292,7 +290,7 @@ def edit_file_size_limits_prompt(manager: Manager, config: Dict) -> None:
config["File_Size_Limits"]["minimum_other_size"] = int(minimum_other_size)
-def edit_ignore_options_prompt(manager: Manager, config: Dict) -> None:
+def edit_ignore_options_prompt(manager: Manager, config: dict) -> None:
"""Edit the ignore options"""
console.clear()
console.print("Editing Ignore Options")
@@ -362,7 +360,7 @@ def edit_ignore_options_prompt(manager: Manager, config: Dict) -> None:
config["Ignore_Options"]["only_hosts"] = only_hosts
-def edit_runtime_options_prompt(manager: Manager, config: Dict) -> None:
+def edit_runtime_options_prompt(manager: Manager, config: dict) -> None:
"""Edit the runtime options"""
console.clear()
console.print("Editing Runtime Options")
@@ -430,7 +428,7 @@ def edit_runtime_options_prompt(manager: Manager, config: Dict) -> None:
config["Runtime_Options"]["console_log_level"] = int(console_log_level)
-def edit_sort_options_prompt(manager: Manager, config: Dict) -> None:
+def edit_sort_options_prompt(manager: Manager, config: dict) -> None:
"""Edit the sort options"""
console.clear()
console.print("Editing Sort Options")
diff --git a/cyberdrop_dl/utils/args/browser_cookie_extraction.py b/cyberdrop_dl/utils/args/browser_cookie_extraction.py
index 3cfb38d98..0cd678ff5 100644
--- a/cyberdrop_dl/utils/args/browser_cookie_extraction.py
+++ b/cyberdrop_dl/utils/args/browser_cookie_extraction.py
@@ -10,8 +10,6 @@ from rich.console import Console
from cyberdrop_dl.utils.dataclasses.supported_domains import SupportedDomains
if TYPE_CHECKING:
- from typing import Dict
-
from cyberdrop_dl.managers.manager import Manager
@@ -43,7 +41,7 @@ def cookie_wrapper(func):
@cookie_wrapper
def get_forum_cookies(manager: Manager, browser: str) -> None:
"""Get the cookies for the forums"""
- auth_args: Dict = manager.config_manager.authentication_data
+ auth_args: dict = manager.config_manager.authentication_data
for forum in SupportedDomains.supported_forums:
try:
cookie = get_cookie(browser, forum)
diff --git a/cyberdrop_dl/utils/args/config_definitions.py b/cyberdrop_dl/utils/args/config_definitions.py
index 6355e4192..317903e20 100644
--- a/cyberdrop_dl/utils/args/config_definitions.py
+++ b/cyberdrop_dl/utils/args/config_definitions.py
@@ -1,10 +1,8 @@
from __future__ import annotations
-from typing import Dict
-
from cyberdrop_dl.managers.path_manager import APP_STORAGE, DOWNLOAD_STORAGE
-authentication_settings: Dict = {
+authentication_settings: dict = {
"Forums": {
"celebforum_xf_user_cookie": "",
"celebforum_username": "",
@@ -57,7 +55,7 @@ authentication_settings: Dict = {
},
}
-settings: Dict = {
+settings: dict = {
"Download_Options": {
"block_download_sub_folders": False,
"disable_download_attempt_limit": False,
@@ -129,7 +127,7 @@ settings: Dict = {
},
}
-global_settings: Dict = {
+global_settings: dict = {
"General": {
"allow_insecure_connections": False,
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:120.0) Gecko/20100101 Firefox/120.0",
diff --git a/cyberdrop_dl/utils/database/tables/hash_table.py b/cyberdrop_dl/utils/database/tables/hash_table.py
index 3dcd69673..469acbcaf 100644
--- a/cyberdrop_dl/utils/database/tables/hash_table.py
+++ b/cyberdrop_dl/utils/database/tables/hash_table.py
@@ -171,7 +171,7 @@ WHERE download_filename = ? AND folder = ?;""",
try:
await cursor.execute("SELECT DISTINCT hash FROM hash")
results = await cursor.fetchall()
- return list(map(lambda x: x[0], results))
+ return [x[0] for x in results]
except Exception as e:
console.print(f"Error retrieving folder and filename: {e}")
return []
diff --git a/cyberdrop_dl/utils/sorting.py b/cyberdrop_dl/utils/sorting.py
index 138f4247f..2341b2caa 100644
--- a/cyberdrop_dl/utils/sorting.py
+++ b/cyberdrop_dl/utils/sorting.py
@@ -157,7 +157,7 @@ class Sorter:
relative_folder = folder.relative_to(self.download_dir)
base_folder = self.download_dir / relative_folder.parts[0]
except Exception as e:
- if e.__class__ == ValueError:
+ if isinstance(e, ValueError):
continue
logger.log(
40,
diff --git a/cyberdrop_dl/utils/transfer/transfer_v4_config.py b/cyberdrop_dl/utils/transfer/transfer_v4_config.py
index 303515ac1..9133bf273 100644
--- a/cyberdrop_dl/utils/transfer/transfer_v4_config.py
+++ b/cyberdrop_dl/utils/transfer/transfer_v4_config.py
@@ -8,7 +8,7 @@ from cyberdrop_dl.managers.manager import Manager
from cyberdrop_dl.utils.args.config_definitions import settings
-def _save_yaml(file: Path, data: Dict) -> None:
+def _save_yaml(file: Path, data: dict) -> None:
"""Saves a dict to a yaml file"""
file.parent.mkdir(parents=True, exist_ok=True)
with open(file, "w") as yaml_file:
diff --git a/cyberdrop_dl/utils/utilities.py b/cyberdrop_dl/utils/utilities.py
index 62d052036..83e98552f 100644
--- a/cyberdrop_dl/utils/utilities.py
+++ b/cyberdrop_dl/utils/utilities.py
@@ -7,7 +7,7 @@ import re
from enum import IntEnum
from functools import wraps
from pathlib import Path
-from typing import TYPE_CHECKING, Union
+from typing import TYPE_CHECKING
import aiofiles
import apprise
@@ -23,8 +23,6 @@ from cyberdrop_dl.managers.real_debrid.errors import RealDebridError
DEFAULT_CONSOLE_WIDTH = 240
if TYPE_CHECKING:
- from typing import Tuple
-
from cyberdrop_dl.managers.manager import Manager
from cyberdrop_dl.scraper.crawler import Crawler
from cyberdrop_dl.utils.dataclasses.url_objects import ScrapeItem
@@ -133,7 +131,7 @@ def error_handling_wrapper(func):
return wrapper
-async def log(message: Union[str, Exception], level: int, sleep: int = None, **kwargs) -> None:
+async def log(message: Exception | str, level: int, sleep: int = None, **kwargs) -> None:
"""Simple logging function"""
logger.log(level, message, **kwargs)
if DEBUG_VAR:
@@ -141,13 +139,13 @@ async def log(message: Union[str, Exception], level: int, sleep: int = None, **k
log_console(level, message, sleep=sleep)
-async def log_debug(message: Union[str, Exception], level: int, sleep: int = None, *kwargs) -> None:
+async def log_debug(message: Exception | str, level: int, sleep: int = None, *kwargs) -> None:
"""Simple logging function"""
if DEBUG_VAR:
logger_debug.log(level, message.encode("ascii", "ignore").decode("ascii"), *kwargs)
-async def log_debug_console(message: Union[str, Exception], level: int, sleep: int = None):
+async def log_debug_console(message: Exception | str, level: int, sleep: int = None):
if CONSOLE_DEBUG_VAR:
log_console(level, message.encode("ascii", "ignore").decode("ascii"), sleep=sleep)
@@ -222,7 +220,7 @@ async def sanitize_folder(title: str) -> str:
return title
-async def get_filename_and_ext(filename: str, forum: bool = False) -> Tuple[str, str]:
+async def get_filename_and_ext(filename: str, forum: bool = False) -> tuple[str, str]:
"""Returns the filename and extension of a given file, throws NoExtensionFailure if there is no extension"""
filename_parts = filename.rsplit(".", 1)
if len(filename_parts) == 1:
@@ -266,7 +264,7 @@ async def _is_number(ext: str):
return False
-async def remove_id(manager: Manager, filename: str, ext: str) -> Tuple[str, str]:
+async def remove_id(manager: Manager, filename: str, ext: str) -> tuple[str, str]:
"""Removes the additional string some websites adds to the end of every filename"""
original_filename = filename
if manager.config_manager.settings_data["Download_Options"]["remove_generated_id_from_filenames"]:
@@ -328,7 +326,7 @@ async def check_partials_and_empty_folders(manager: Manager):
await purge_dir_tree(manager.path_manager.sorted_dir)
-async def check_latest_pypi(log_to_console: bool = True, call_from_ui: bool = False) -> Tuple[str]:
+async def check_latest_pypi(log_to_console: bool = True, call_from_ui: bool = False) -> tuple[str]:
"""Checks if the current version is the latest version"""
import json
import urllib.request
@@ -462,7 +460,7 @@ async def sent_apprise_notifications(manager: Manager) -> None:
rich.print("Apprise notifications results:", result)
-def parse_bytes(size: int) -> Tuple[int, str]:
+def parse_bytes(size: int) -> tuple[int, str]:
for unit in ["B", "KB", "MB", "GB", "TB", "PB", "EB"]:
if size < 1024:
return size, unit