Bulk asynchronous downloader for multiple file hosts
Python asynciobunkrcyberdropdownloaderdropboxfilestergofilegoogle-drivemediafiremegamega-nzonedrivepatreonpawchivepinterestpixeldraintransfer-ittwitchtwittervk
refactor: report downloads with no content type as `InvalidContentType` (#693)
NTFSvolumeadf22eca7335
diff --git a/cyberdrop_dl/clients/download_client.py b/cyberdrop_dl/clients/download_client.pyindex 24ead3851..5335776d4 100644--- a/cyberdrop_dl/clients/download_client.py+++ b/cyberdrop_dl/clients/download_client.py@@ -6,7 +6,6 @@ import itertoolsimport timefrom functools import partial, wrapsfrom http import HTTPStatus-from pathlib import Pathfrom typing import TYPE_CHECKINGimport aiofiles@@ -26,8 +25,11 @@ from cyberdrop_dl.utils.logger import log, log_debugif TYPE_CHECKING:from collections.abc import Callable, Coroutine+ from pathlib import Pathfrom typing import Any+ from multidict import CIMultiDictProxy+from cyberdrop_dl.managers.client_manager import ClientManagerfrom cyberdrop_dl.managers.manager import Managerfrom cyberdrop_dl.utils.data_enums_classes.url_objects import MediaItem@@ -187,11 +189,7 @@ class DownloadClient:media_item.partial_file.unlink()await self.client_manager.check_http_status(resp, download=True, origin=media_item.url)- content_type = resp.headers.get("Content-Type", "")- override = next(- (override for type, override in CONTENT_TYPES_OVERRIDES.items() if type in content_type), None- )- content_type = override or content_type+ _ = get_content_type(media_item.ext, resp.headers)media_item.filesize = int(resp.headers.get("Content-Length", "0"))if not media_item.complete_file:@@ -208,15 +206,6 @@ class DownloadClient:return False- ext = Path(media_item.filename).suffix.lower()- if (- content_type- and any(s in content_type.lower() for s in ("html", "text"))- and ext not in FILE_FORMATS["Text"]- ):- msg = f"Received '{content_type}', was expecting other"- raise InvalidContentTypeError(message=msg)-if resp.status != HTTPStatus.PARTIAL_CONTENT and media_item.partial_file.is_file():media_item.partial_file.unlink()@@ -475,3 +464,25 @@ class DownloadClient:@file_path.setterdef file_path(self, media_item: MediaItem):self._file_path = media_item.filename+++def get_content_type(ext: str, headers: CIMultiDictProxy) -> str:+ content_type: str = headers.get("Content-Type", "")+ if not content_type:+ msg = "No content type in response headers"+ raise InvalidContentTypeError(message=msg)++ override_key = next((name for name in CONTENT_TYPES_OVERRIDES if name in content_type), "<NO_OVERRIDE>")+ override: str | None = CONTENT_TYPES_OVERRIDES.get(override_key)+ 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"]:+ msg = f"Received '{content_type}', was expecting other"+ raise InvalidContentTypeError(message=msg)++ return content_type+++def is_html_or_text(content_type: str) -> bool:+ return any(s in content_type for s in ("html", "text"))diff --git a/cyberdrop_dl/managers/client_manager.py b/cyberdrop_dl/managers/client_manager.pyindex 457e9231e..3a0360adf 100644--- a/cyberdrop_dl/managers/client_manager.py+++ b/cyberdrop_dl/managers/client_manager.py@@ -20,7 +20,6 @@ from cyberdrop_dl.clients.errors import DDOSGuardError, DownloadError, ScrapeErrfrom cyberdrop_dl.clients.scraper_client import ScraperClientfrom cyberdrop_dl.managers.download_speed_manager import DownloadSpeedLimiterfrom cyberdrop_dl.ui.prompts.user_prompts import get_cookies_from_browsers-from cyberdrop_dl.utils.constants import CustomHTTPStatusfrom cyberdrop_dl.utils.logger import log, log_spacerif TYPE_CHECKING:@@ -153,6 +152,7 @@ class ClientManager:"""Checks the HTTP status code and raises an exception if it's not acceptable."""status = response.statusheaders = response.headers+ message = Noneif download and headers.get("ETag") in DOWNLOAD_ERROR_ETAGS:message = DOWNLOAD_ERROR_ETAGS.get(headers.get("ETag"))@@ -161,10 +161,10 @@ class ClientManager:if HTTPStatus.OK <= status < HTTPStatus.BAD_REQUEST:return- if any(domain in response.url.host for domain in ("gofile", "imgur")):+ if any(domain in response.url.host for domain in ("gofile", "imgur")): # type: ignorewith contextlib.suppress(ContentTypeError):JSON_Resp: dict = await response.json()- status = JSON_Resp.get("status")+ status: str | int = JSON_Resp.get("status") # type: ignoreif status and isinstance(status, str) and "notFound" in status:raise ScrapeError(404, origin=origin)data = JSON_Resp.get("data")@@ -179,8 +179,6 @@ class ClientManager:soup = BeautifulSoup(response_text, "html.parser")if cls.check_ddos_guard(soup) or cls.check_cloudflare(soup):raise DDOSGuardError(origin=origin)- status = status if headers.get("Content-Type") else CustomHTTPStatus.IM_A_TEAPOT- message = None if headers.get("Content-Type") else "No content-type in response header"raise DownloadError(status=status, message=message, origin=origin)