Skip to content

Bulk asynchronous downloader for multiple file hosts

refactor: add scrape_item to check_http_status

NTFSvolumebf24b2f3ad0b
diff --git a/cyberdrop_dl/clients/errors.py b/cyberdrop_dl/clients/errors.py
index 5a55a477b..67c721cd5 100644
--- a/cyberdrop_dl/clients/errors.py
+++ b/cyberdrop_dl/clients/errors.py
@@ -23,54 +23,65 @@ class CDLBaseException(Exception):
super().__init__(self.status)
class InvalidContentTypeFailure(CDLBaseException):
- def __init__(self, *, message: str = "Invalid Content Type", origin: Optional[ScrapeItem | URL] = None):
+ def __init__(self, *, message: Optional [str] = None, origin: Optional[ScrapeItem | URL] = None):
"""This error will be thrown when the content type isn't as expected"""
ui_message = "Invalid Content Type"
+ message = message or ui_message
super().__init__(ui_message, message = message, origin=origin)
class NoExtensionFailure(CDLBaseException):
- def __init__(self, *, message: str = "No File Extension", origin: Optional[ScrapeItem | URL] = None):
+ def __init__(self, *, message: Optional [str] = None, origin: Optional[ScrapeItem | URL] = None):
"""This error will be thrown when no extension is given for a file"""
ui_message = "No File Extension"
+ message = message or ui_message
super().__init__(ui_message, message = message, origin=origin)
class PasswordProtected(CDLBaseException):
- def __init__(self, *, message: str = "File/Folder is password protected", origin: Optional[ScrapeItem | URL] = None ):
+ def __init__(self, *, message: Optional[str] = None, origin: Optional[ScrapeItem | URL] = None ):
"""This error will be thrown when a file is password protected"""
ui_message = "Password Protected"
+ message = message or "File/Folder is password protected"
super().__init__(ui_message, message = message, origin=origin)
class DDOSGuardFailure(CDLBaseException):
- def __init__(self, *, message: str = "DDoS-Guard detected", origin: Optional[ScrapeItem | URL] = None):
+ def __init__(self, *, message: Optional[str] = None, origin: Optional[ScrapeItem | URL] = None):
"""This error will be thrown when DDoS-Guard is detected"""
ui_message = "DDoS-Guard"
+ message = message or "DDoS-Guard detected"
super().__init__(ui_message, message = message, origin=origin)
class DownloadFailure(CDLBaseException):
- def __init__(self, status: int, message: Optional[str] = "Download Failure" , origin: Optional[ScrapeItem | URL] = None):
- """This error will be thrown when a request fails"""
- try:
- ui_message = f"{status} {HTTPStatus(status).phrase}" if isinstance (status, int) else status
- except ValueError:
- ui_message = status
+ def __init__(self, status: int, message: Optional[str] = None , origin: Optional[ScrapeItem | URL] = None):
+ """This error will be thrown when a download fails"""
+ ui_message = status
+ if isinstance (status, int):
+ try:
+ ui_message = f"{status} {HTTPStatus(status).phrase}"
+ except ValueError:
+ ui_message = f"{status} HTTP Error"
+ message = message or ui_message
super().__init__(ui_message, message = message, status = status, origin=origin)
class ScrapeFailure(CDLBaseException):
- def __init__(self, status: int, message: Optional[str] = "Scrape Failure" , origin: Optional[ScrapeItem | URL] = None):
+ def __init__(self, status: int, message: Optional[str] = None, origin: Optional[ScrapeItem | URL] = None):
"""This error will be thrown when a scrape fails"""
- try:
- ui_message = f"{status} {HTTPStatus(status).phrase}" if isinstance (status, int) else status
- except ValueError:
- ui_message = status
+ ui_message = status
+ if isinstance (status, int):
+ try:
+ ui_message = f"{status} {HTTPStatus(status).phrase}"
+ except ValueError:
+ ui_message = f"{status} HTTP Error"
+ message = message or ui_message
super().__init__(ui_message, message = message, status = status, origin=origin)
class FailedLoginFailure(CDLBaseException):
- def __init__(self, *, message: str = "Failed Login", origin: Optional[ScrapeItem | URL] = None):
+ def __init__(self, *, message: Optional[str] = None , origin: Optional[ScrapeItem | URL] = None):
"""This error will be thrown when the login fails for a site"""
ui_message = "Failed Login"
+ message = message or ui_message
super().__init__(ui_message, message = message, origin=origin)
diff --git a/cyberdrop_dl/managers/client_manager.py b/cyberdrop_dl/managers/client_manager.py
index 5363a24c3..3de5cbbe5 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
+from typing import TYPE_CHECKING, Optional
import aiohttp
import certifi
@@ -18,8 +18,15 @@ from cyberdrop_dl.utils.utilities import CustomHTTPStatus
if TYPE_CHECKING:
from cyberdrop_dl.managers.manager import Manager
+ from cyberdrop_dl.scraper.crawler import ScrapeItem
+ from yarl import URL
+DOWNLOAD_ERROR_ETAGS = {
+ "d835884373f4d6c8f24742ceabe74946": "Imgur image has been removed",
+ "65b7753c-528a":"SC Scrape Image"
+}
+
class ClientManager:
"""Creates a 'client' that can be referenced by scraping or download sessions"""
@@ -80,49 +87,37 @@ class ClientManager:
"""~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"""
- async def check_http_status(self, response: ClientResponse, download: bool = False) -> None:
+ async def check_http_status(self, response: ClientResponse, download: bool = False, scrape_item: Optional[ScrapeItem | URL]= None) -> None:
"""Checks the HTTP status code and raises an exception if it's not acceptable"""
status = response.status
headers = response.headers
- if download:
- if headers.get('ETag') == '"d835884373f4d6c8f24742ceabe74946"':
- raise DownloadFailure(status=HTTPStatus.NOT_FOUND, message="Imgur image has been removed")
- if headers.get('ETag') == '"65b7753c-528a"':
- raise DownloadFailure(status=HTTPStatus.NOT_FOUND, message="SC Scrape Image")
+ if download and headers.get('ETag') in DOWNLOAD_ERROR_ETAGS:
+ message = DOWNLOAD_ERROR_ETAGS.get(headers.get('ETag'))
+ raise DownloadFailure(HTTPStatus.NOT_FOUND, message=message, origin = scrape_item)
if HTTPStatus.OK <= status < HTTPStatus.BAD_REQUEST:
return
-
- if "gofile" in response.url.host.lower():
+
+ if any({domain in response.url.host.lower() for domain in ("gofile","imgur")}):
try:
- JSON_Resp = await response.json()
- if "notFound" in JSON_Resp["status"]:
- raise ScrapeFailure(404, "Does Not Exist")
- except ContentTypeError:
- pass
-
- if "imgur" in response.url.host.lower():
- try:
- JSON_Resp = await response.json()
+ JSON_Resp: dict = await response.json()
if "status" in JSON_Resp:
- raise ScrapeFailure(JSON_Resp['status'], JSON_Resp['data']['error'])
+ if "notFound" in JSON_Resp["status"]:
+ raise ScrapeFailure(HTTPStatus.NOT_FOUND, origin = scrape_item)
+ if JSON_Resp.get('data') and 'error' in JSON_Resp['data']:
+ raise ScrapeFailure(JSON_Resp['status'], JSON_Resp['data']['error'], origin = scrape_item)
except ContentTypeError:
pass
- try:
- phrase = HTTPStatus(status).phrase
- except ValueError:
- phrase = "Unknown"
-
response_text = await response.text()
if "<title>DDoS-Guard</title>" in response_text:
- raise DDOSGuardFailure(status="DDOS-Guard", message="DDoS-Guard detected")
+ raise DDOSGuardFailure(origin = scrape_item)
if not headers.get('Content-Type'):
- raise DownloadFailure(status=CustomHTTPStatus.IM_A_TEAPOT, message="No content-type in response header")
+ raise DownloadFailure(status=CustomHTTPStatus.IM_A_TEAPOT, message="No content-type in response header", origin = scrape_item)
- raise DownloadFailure(status=status, message=f"HTTP status code {status}: {phrase}")
+ raise DownloadFailure(status=status, origin = scrape_item )
async def check_bunkr_maint(self, headers):
if headers.get('Content-Length') == "322509" and headers.get('Content-Type') == "video/mp4":