Skip to content

Bulk asynchronous downloader for multiple file hosts

refactor: use frozen file extensions (#72)

NTFSvolume30129833a3c7
diff --git a/cyberdrop_dl/clients/download_client.py b/cyberdrop_dl/clients/download_client.py
index 2ceb82aa4..71ccb4371 100644
--- a/cyberdrop_dl/clients/download_client.py
+++ b/cyberdrop_dl/clients/download_client.py
@@ -13,7 +13,7 @@ import aiofiles
from cyberdrop_dl import aio, constants, storage
from cyberdrop_dl.clients.response import AbstractResponse
-from cyberdrop_dl.constants import FILE_FORMATS
+from cyberdrop_dl.constants import FileExt
from cyberdrop_dl.data_structures.url_objects import AbsoluteHttpURL
from cyberdrop_dl.exceptions import DDOSGuardError, DownloadError, InvalidContentTypeError, SlowDownloadError
from cyberdrop_dl.utils import dates
@@ -482,9 +482,9 @@ class DownloadClient:
min_other_filesize = file_size_limits.minimum_other_size
assert media.filesize is not None
- if media.ext in FILE_FORMATS["Images"]:
+ if media.ext in FileExt.IMAGE:
proceed = min_image_filesize < media.filesize < max_image_filesize
- elif media.ext in FILE_FORMATS["Videos"]:
+ elif media.ext in FileExt.VIDEO:
proceed = min_video_filesize < media.filesize < max_video_filesize
else:
proceed = min_other_filesize < media.filesize < max_other_filesize
@@ -507,7 +507,7 @@ def get_content_type(ext: str, headers: Mapping[str, str]) -> str | None:
content_type = override or content_type
content_type = content_type.lower()
- if is_html_or_text(content_type) and ext.lower() not in FILE_FORMATS["Text"]:
+ if is_html_or_text(content_type) and ext.lower() not in FileExt.TEXT:
msg = f"Received '{content_type}', was expecting other"
raise InvalidContentTypeError(message=msg)
diff --git a/cyberdrop_dl/constants.py b/cyberdrop_dl/constants.py
index 49c8159d9..bf61711c7 100644
--- a/cyberdrop_dl/constants.py
+++ b/cyberdrop_dl/constants.py
@@ -3,7 +3,7 @@ from dataclasses import field
from datetime import UTC, datetime
from enum import auto
from pathlib import Path
-from typing import TYPE_CHECKING, Any, Final
+from typing import TYPE_CHECKING, Final, final
from aiohttp.resolver import AsyncResolver, ThreadedResolver
from rich.text import Text
@@ -31,13 +31,7 @@ MAX_NAME_LENGTHS = {"FILE": 95, "FOLDER": 60}
DEFAULT_CONSOLE_WIDTH = 240
CSV_DELIMITER = ","
LOG_OUTPUT_TEXT = Text("")
-RICH_HANDLER_CONFIG: dict[str, Any] = {"rich_tracebacks": True, "tracebacks_show_locals": False}
-RICH_HANDLER_DEBUG_CONFIG = RICH_HANDLER_CONFIG | {
- "tracebacks_show_locals": True,
- "locals_max_string": DEFAULT_CONSOLE_WIDTH,
- "tracebacks_extra_lines": 2,
- "locals_max_length": 20,
-}
+
VALIDATION_ERROR_FOOTER = """Please delete the file or fix the errors. Read the documentation to learn what's the expected format and values: https://script-ware.gitbook.io/cyberdrop-dl/reference/configuration-options
\nThis is not a bug. Do not open issues related to this"""
@@ -128,74 +122,82 @@ class NotificationResult(Enum):
NONE = Text("No Notifications Sent", "yellow")
-# file formats
-FILE_FORMATS = {
- "Images": {
- ".gif",
- ".gifv",
- ".heic",
- ".jfif",
- ".jif",
- ".jpe",
- ".jpeg",
- ".jpg",
- ".jxl",
- ".png",
- ".svg",
- ".tif",
- ".tiff",
- ".webp",
- },
- "Videos": {
- ".3gp",
- ".avchd",
- ".avi",
- ".f4v",
- ".flv",
- ".m2ts",
- ".m4p",
- ".m4v",
- ".mkv",
- ".mov",
- ".mp2",
- ".mp4",
- ".mpe",
- ".mpeg",
- ".mpg",
- ".mpv",
- ".mts",
- ".ogg",
- ".ogv",
- ".qt",
- ".swf",
- ".ts",
- ".webm",
- ".wmv",
- },
- "Audio": {
- ".flac",
- ".m4a",
- ".mka",
- ".mp3",
- ".wav",
- },
- "Text": {
- ".htm",
- ".html",
- ".md",
- ".nfo",
- ".txt",
- ".vtt",
- ".sub",
- },
- "7z": {
- ".7z",
- ".bz2",
- ".gz",
- ".tar",
- ".zip",
- },
-}
-
-
-MEDIA_EXTENSIONS = FILE_FORMATS["Audio"] | FILE_FORMATS["Videos"] | FILE_FORMATS["Images"]
+@final
+class FileExt:
+ IMAGE = frozenset(
+ {
+ ".gif",
+ ".gifv",
+ ".heic",
+ ".jfif",
+ ".jif",
+ ".jpe",
+ ".jpeg",
+ ".jpg",
+ ".jxl",
+ ".png",
+ ".svg",
+ ".tif",
+ ".tiff",
+ ".webp",
+ }
+ )
+ VIDEO = frozenset(
+ {
+ ".3gp",
+ ".avchd",
+ ".avi",
+ ".f4v",
+ ".flv",
+ ".m2ts",
+ ".m4p",
+ ".m4v",
+ ".mkv",
+ ".mov",
+ ".mp2",
+ ".mp4",
+ ".mpe",
+ ".mpeg",
+ ".mpg",
+ ".mpv",
+ ".mts",
+ ".ogg",
+ ".ogv",
+ ".qt",
+ ".swf",
+ ".ts",
+ ".webm",
+ ".wmv",
+ }
+ )
+ AUDIO = frozenset(
+ {
+ ".flac",
+ ".m4a",
+ ".mka",
+ ".mp3",
+ ".wav",
+ }
+ )
+ TEXT = frozenset(
+ {
+ ".htm",
+ ".html",
+ ".md",
+ ".nfo",
+ ".txt",
+ ".vtt",
+ ".sub",
+ }
+ )
+ SEVEN_Z = frozenset(
+ {
+ ".7z",
+ ".bz2",
+ ".gz",
+ ".tar",
+ ".zip",
+ }
+ )
+ VIDEO_OR_IMAGE = VIDEO | IMAGE
+ MEDIA = AUDIO | VIDEO_OR_IMAGE
diff --git a/cyberdrop_dl/crawlers/bunkrr.py b/cyberdrop_dl/crawlers/bunkrr.py
index 79791d47c..4d4cae1f7 100644
--- a/cyberdrop_dl/crawlers/bunkrr.py
+++ b/cyberdrop_dl/crawlers/bunkrr.py
@@ -10,7 +10,7 @@ from typing import TYPE_CHECKING, Any, ClassVar
from aiohttp import ClientConnectorError
-from cyberdrop_dl.constants import FILE_FORMATS
+from cyberdrop_dl.constants import FileExt
from cyberdrop_dl.crawlers.crawler import Crawler, RateLimit, SupportedPaths, auto_task_id
from cyberdrop_dl.data_structures.url_objects import AbsoluteHttpURL
from cyberdrop_dl.exceptions import DDOSGuardError
@@ -35,7 +35,6 @@ class Selector:
IMAGE_PREVIEW = "img.max-h-full.w-auto.object-cover.relative"
-VIDEO_AND_IMAGE_EXTS: set[str] = FILE_FORMATS["Images"] | FILE_FORMATS["Videos"]
_HOST_OPTIONS: frozenset[str] = frozenset(("bunkr.site", "bunkr.cr", "bunkr.ph"))
_DEEP_SCRAPE_CDNS: frozenset[str] = frozenset(
(
@@ -101,7 +100,7 @@ class File:
src = thumb.with_path(thumb.path.replace("/thumbs/", "/")).with_suffix(Path(self.name).suffix)
- if src.suffix.lower() not in FILE_FORMATS["Images"]:
+ if src.suffix.lower() not in FileExt.IMAGE:
src = src.with_host(src.host.replace("i-", ""))
self.src = _override_cdn(src)
@@ -177,7 +176,7 @@ class BunkrrCrawler(Crawler):
return
deep_scrape = (
- src.suffix.lower() not in VIDEO_AND_IMAGE_EXTS
+ src.suffix.lower() not in FileExt.VIDEO_OR_IMAGE
or "no-image" in src.name
or self.deep_scrape
or any(cdn in src.host for cdn in _DEEP_SCRAPE_CDNS)
diff --git a/cyberdrop_dl/crawlers/http_direct.py b/cyberdrop_dl/crawlers/http_direct.py
index 08f703e0b..863601202 100644
--- a/cyberdrop_dl/crawlers/http_direct.py
+++ b/cyberdrop_dl/crawlers/http_direct.py
@@ -2,7 +2,7 @@ from __future__ import annotations
from typing import TYPE_CHECKING, ClassVar
-from cyberdrop_dl.constants import FILE_FORMATS
+from cyberdrop_dl.constants import FileExt
from cyberdrop_dl.crawlers.crawler import Crawler
from cyberdrop_dl.exceptions import NoExtensionError
from cyberdrop_dl.utils.utilities import get_filename_and_ext
@@ -11,9 +11,6 @@ if TYPE_CHECKING:
from cyberdrop_dl.data_structures.url_objects import ScrapeItem
-MEDIA_EXTENSIONS = FILE_FORMATS["Images"] | FILE_FORMATS["Videos"] | FILE_FORMATS["Audio"]
-
-
class DirectHttpFile(Crawler, is_generic=True):
DOMAIN: ClassVar[str] = "no_crawler"
@@ -23,7 +20,7 @@ class DirectHttpFile(Crawler, is_generic=True):
except NoExtensionError:
filename, ext = get_filename_and_ext(scrape_item.url.name, forum=True)
- if ext not in MEDIA_EXTENSIONS:
+ if ext not in FileExt.MEDIA:
raise ValueError
scrape_item.add_to_parent_title("Loose Files")
diff --git a/cyberdrop_dl/downloader/downloader.py b/cyberdrop_dl/downloader/downloader.py
index a17200aee..a0710bfaf 100644
--- a/cyberdrop_dl/downloader/downloader.py
+++ b/cyberdrop_dl/downloader/downloader.py
@@ -333,7 +333,7 @@ class Downloader:
async def check_file_can_download(self, media_item: MediaItem) -> None:
"""Checks if the file can be downloaded."""
await storage.check(media_item)
- if not self.manager.client_manager.check_allowed_filetype(media_item):
+ if not self.manager.client_manager.is_allowed_filetype(media_item):
raise RestrictedFiletypeError(origin=media_item)
if not await self.manager.client_manager.check_file_duration(media_item):
raise DurationError(origin=media_item)
diff --git a/cyberdrop_dl/managers/client_manager.py b/cyberdrop_dl/managers/client_manager.py
index a9b10c073..f0715feae 100644
--- a/cyberdrop_dl/managers/client_manager.py
+++ b/cyberdrop_dl/managers/client_manager.py
@@ -23,6 +23,7 @@ from cyberdrop_dl.clients import HTTPClient
from cyberdrop_dl.clients.download_client import DownloadClient
from cyberdrop_dl.clients.flaresolverr import FlareSolverrClient
from cyberdrop_dl.clients.response import AbstractResponse
+from cyberdrop_dl.constants import FileExt
from cyberdrop_dl.data_structures.url_objects import AbsoluteHttpURL, MediaItem
from cyberdrop_dl.exceptions import DDOSGuardError, DownloadError, ScrapeError, TooManyCrawlerErrors
from cyberdrop_dl.ffmpeg import probe
@@ -45,9 +46,7 @@ except ImportError as e:
_curl_import_error = e
logger = logging.getLogger(__name__)
-_VALID_EXTENSIONS = (
- constants.FILE_FORMATS["Images"] | constants.FILE_FORMATS["Videos"] | constants.FILE_FORMATS["Audio"]
-)
+
_DOWNLOAD_ERROR_ETAGS = {
"d835884373f4d6c8f24742ceabe74946": "Imgur image has been removed",
@@ -210,17 +209,17 @@ class ClientManager:
token = b64encode(f"{username}:{password}".encode()).decode("ascii")
return f"Basic {token}"
- def check_allowed_filetype(self, media_item: MediaItem) -> bool:
+ def is_allowed_filetype(self, media_item: MediaItem) -> bool:
"""Checks if the file type is allowed to download."""
ignore_options = self.manager.config_manager.settings_data.ignore_options
+ ext = media_item.ext.lower()
- if media_item.ext.lower() in constants.FILE_FORMATS["Images"] and ignore_options.exclude_images:
- return False
- if media_item.ext.lower() in constants.FILE_FORMATS["Videos"] and ignore_options.exclude_videos:
- return False
- if media_item.ext.lower() in constants.FILE_FORMATS["Audio"] and ignore_options.exclude_audio:
- return False
- return not (ignore_options.exclude_other and media_item.ext.lower() not in _VALID_EXTENSIONS)
+ return not (
+ (ignore_options.exclude_images and ext in FileExt.IMAGE)
+ or (ignore_options.exclude_videos and ext in FileExt.VIDEO)
+ or (ignore_options.exclude_audio and ext in FileExt.AUDIO)
+ or (ignore_options.exclude_other and ext not in FileExt.MEDIA)
+ )
def check_allowed_date_range(self, media_item: MediaItem) -> bool:
"""Checks if the file was uploaded within the config date range"""
@@ -392,8 +391,8 @@ class ClientManager:
if media_item.is_segment:
return True
- is_video = media_item.ext.lower() in constants.FILE_FORMATS["Videos"]
- is_audio = media_item.ext.lower() in constants.FILE_FORMATS["Audio"]
+ is_video = media_item.ext.lower() in FileExt.VIDEO
+ is_audio = media_item.ext.lower() in FileExt.AUDIO
if not (is_video or is_audio):
return True
diff --git a/cyberdrop_dl/utils/sorting.py b/cyberdrop_dl/utils/sorting.py
index 79e6342a5..142f062f0 100644
--- a/cyberdrop_dl/utils/sorting.py
+++ b/cyberdrop_dl/utils/sorting.py
@@ -11,7 +11,7 @@ from typing import TYPE_CHECKING, Any
import imagesize
from cyberdrop_dl import constants
-from cyberdrop_dl.constants import FILE_FORMATS
+from cyberdrop_dl.constants import FileExt
from cyberdrop_dl.ffmpeg import probe
from cyberdrop_dl.utils import strings
from cyberdrop_dl.utils.logger import log_with_color
@@ -104,11 +104,11 @@ class Sorter:
if ext in constants.TempExt:
continue
- if ext in FILE_FORMATS["Audio"]:
+ if ext in FileExt.AUDIO:
await self.sort_audio(file, folder_name)
- elif ext in FILE_FORMATS["Images"]:
+ elif ext in FileExt.IMAGE:
await self.sort_image(file, folder_name)
- elif ext in FILE_FORMATS["Videos"]:
+ elif ext in FileExt.VIDEO:
await self.sort_video(file, folder_name)
else:
await self.sort_other(file, folder_name)
diff --git a/cyberdrop_dl/utils/utilities.py b/cyberdrop_dl/utils/utilities.py
index c766a0341..5dffa87e3 100644
--- a/cyberdrop_dl/utils/utilities.py
+++ b/cyberdrop_dl/utils/utilities.py
@@ -37,6 +37,7 @@ from pydantic import ValidationError
from yarl import URL
from cyberdrop_dl import constants
+from cyberdrop_dl.constants import FileExt
from cyberdrop_dl.data_structures import AbsoluteHttpURL
from cyberdrop_dl.exceptions import (
CDLBaseError,
@@ -241,7 +242,7 @@ def get_filename_and_ext(filename: str, forum: bool = False, mime_type: str | No
ext = ext.rsplit(".")[0]
ext_w_dot = f".{ext}".lower()
full_name = f"{name}.{ext}"
- if ext_w_dot not in constants.MEDIA_EXTENSIONS:
+ if ext_w_dot not in FileExt.MEDIA:
raise InvalidExtensionError(full_name)
filename_as_path = Path(full_name)
@@ -275,7 +276,7 @@ def remove_file_id(manager: Manager, filename: str, ext: str) -> str:
if re.match(constants.RAR_MULTIPART_PATTERN, tail_no_dot) and ext == ".rar" and "-" in filename:
filename, part = filename.rsplit("-", 1)
filename = f"{filename}.{part}"
- elif ext_no_dot.isdigit() and tail in constants.FILE_FORMATS["7z"] and "-" in filename:
+ elif ext_no_dot.isdigit() and tail in FileExt.SEVEN_Z and "-" in filename:
filename, _7z_ext = filename.rsplit("-", 1)
filename = f"{filename}.{_7z_ext}"
if not filename.endswith(ext):