Bulk asynchronous downloader for multiple file hosts
Python asynciobunkrcyberdropdownloaderdropboxfilestergofilegoogle-drivemediafiremegamega-nzonedrivepatreonpawchivepinterestpixeldraintransfer-ittwitchtwittervk
Consolidated client sessions creation and access to it's own classes and file. Implemented request throttling (downloading) and request ratelimiting (scraping)
Jules-WinnfieldXe1a0b5800760
diff --git a/README.md b/README.mdindex 3aa1fd685..e5834a5b3 100644--- a/README.md+++ b/README.md@@ -58,10 +58,10 @@ It will begin to download everything.4. Enjoy!## Custom way (Pip install above)-If you know what you're doing, you can use some of the available options to adjust how the program runs.+If you know what you're doing, you can use the available options to adjust how the program runs.```$ cyberdrop-dl -h-usage: cyberdrop-dl [-h] [-V] [-i INPUT_FILE] [-o OUTPUT_FOLDER] [--log-file LOG_FILE] [--threads THREADS] [--attempts ATTEMPTS] [--include-id] [link ...]+usage: cyberdrop-dl [-h] [-V] [-i INPUT_FILE] [-o OUTPUT_FOLDER] [--log-file LOG_FILE] [--threads THREADS] [--attempts ATTEMPTS] [--include-id] [--exclude-videos] [--exclude-images] [--exclude-audio] [--exclude-other] [--ignore-history] [--thotsbay-username "USERNAME"] [--thotsbay-password "PASSWORD"] [--skip SITE] [link ...]Bulk downloader for multiple file hosts@@ -86,22 +86,11 @@ optional arguments:--ignore-history ignores previous history and downloads everything--thotsbay-username username to login to thotsbay (only required if the thread requires it)--thotsbay-password password to login to thotsbay (only required if the thread requires it)- --cyberfile-username username for cyberfile (used to access the api)- --cyberfile-password password for cyberfile (used to access the api)- --skip-anonfiles this removes anonfile links from downloads- --skip-bunkr this removes bunkr links from downloads- --skip-coomer this removes coomer links from downloads- --skip-cyberdrop this removes cyberdrop links from downloads- --skip-cyberfile this removes cyberfile links from downloads- --skip-erome this removes erome links from downloads- --skip-gfycat this removes gfycat links from downloads- --skip-gofile this removes gofile links from downloads- --skip-jpgchurch this removes jpgchurch links from downloads- --skip-kemono this removes kemono links from downloads- --skip-pixeldrain this removes pixeldrain links from downloads- --skip-pixl this removes pixl links from downloads- --skip-putmega this removes putmega links from downloads- --skip-redgif this removes redgif links from downloads- --skip-saint this removes saint links from downloads-+ --skip this removes the specified hosts links from downloads+ --ratelimit this will add a ratelimiter to requests made in the program, the number you provide is in seconds```+--skip can use: "anonfiles", "bunkr", "coomer.party", "cyberdrop", "cyberfile",+ "erome", "gfycat", "gofile", "jpg.church", "kemono.party",+ "pixeldrain", "pixl.is", "putme.ga", "putmega.com", "redgifs",+ "saint", "thotsbay"+diff --git a/cyberdrop_dl/utils/__init__.py b/cyberdrop_dl/base_functions/__init__.pysimilarity index 100%rename from cyberdrop_dl/utils/__init__.pyrename to cyberdrop_dl/base_functions/__init__.pydiff --git a/cyberdrop_dl/utils/base_functions.py b/cyberdrop_dl/base_functions/base_functions.pysimilarity index 92%rename from cyberdrop_dl/utils/base_functions.pyrename to cyberdrop_dl/base_functions/base_functions.pyindex a4a776f10..e534cb18a 100644--- a/cyberdrop_dl/utils/base_functions.py+++ b/cyberdrop_dl/base_functions/base_functions.py@@ -1,9 +1,7 @@import loggingimport osimport re-import ssl-import certififrom colorama import Fore, Stylefrom yarl import URL@@ -30,9 +28,6 @@ FILE_FORMATS = {}}-user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.75 Safari/537.36'-ssl_context = ssl.create_default_context(cafile=certifi.where())-MAX_FILENAME_LENGTH = 100logger = logging.getLogger(__name__)diff --git a/cyberdrop_dl/utils/data_classes.py b/cyberdrop_dl/base_functions/data_classes.pysimilarity index 99%rename from cyberdrop_dl/utils/data_classes.pyrename to cyberdrop_dl/base_functions/data_classes.pyindex 2d9ed0add..cd29dfd10 100644--- a/cyberdrop_dl/utils/data_classes.py+++ b/cyberdrop_dl/base_functions/data_classes.py@@ -71,7 +71,6 @@ class DomainItem:class CascadeItem:"""Class for keeping track of domains for each scraper type"""domains: Dict[str, DomainItem]- cookies: aiohttp.CookieJar = Noneasync def add_albums(self, domain_item: DomainItem):domain = domain_item.domaindiff --git a/cyberdrop_dl/utils/sql_helper.py b/cyberdrop_dl/base_functions/sql_helper.pysimilarity index 100%rename from cyberdrop_dl/utils/sql_helper.pyrename to cyberdrop_dl/base_functions/sql_helper.pydiff --git a/cyberdrop_dl/utils/crawlers/__init__.py b/cyberdrop_dl/client/__init__.pysimilarity index 100%rename from cyberdrop_dl/utils/crawlers/__init__.pyrename to cyberdrop_dl/client/__init__.pydiff --git a/cyberdrop_dl/client/client.py b/cyberdrop_dl/client/client.pynew file mode 100644index 000000000..ad0a0a4c8--- /dev/null+++ b/cyberdrop_dl/client/client.py@@ -0,0 +1,127 @@+import asyncio+import json+import logging+import ssl+from pathlib import Path++import aiofiles+from bs4 import BeautifulSoup+from yarl import URL++import aiohttp+import certifi+from tqdm import tqdm++from .rate_limiting import AsyncRateLimiter, throttle+from ..base_functions.base_functions import logger+from ..base_functions.data_classes import FileLock+++class Client:+ def __init__(self, ratelimit: int, throttle: int):+ self.ratelimit = ratelimit+ self.throttle = throttle+ self.user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.75 Safari/537.36'+ self.ssl_context = ssl.create_default_context(cafile=certifi.where())+ self.cookies = aiohttp.CookieJar(quote_cookie=False)+++class Session:+ def __init__(self, client: Client) -> None:+ self.client = client+ self.rate_limiter = AsyncRateLimiter(self.client.ratelimit)+ self.headers = {"user-agent": client.user_agent}+ self.client_session = aiohttp.ClientSession(headers=self.headers, raise_for_status=True,+ cookie_jar=self.client.cookies)++ async def get_BS4(self, url: URL):+ async with self.rate_limiter:+ async with self.client_session.get(url, ssl=self.client.ssl_context) as response:+ text = await response.text()+ soup = BeautifulSoup(text, 'html.parser')+ return soup++ async def get_text(self, url: URL):+ async with self.rate_limiter:+ async with self.client_session.get(url, ssl=self.client.ssl_context) as response:+ text = await response.text()+ return text++ async def get_json(self, url: URL):+ async with self.rate_limiter:+ async with self.client_session.get(url, ssl=self.client.ssl_context) as response:+ content = json.loads(await response.content.read())+ return content++ async def post_no_resp(self, url: URL, headers: dict):+ async with self.rate_limiter:+ async with self.client_session.get(url, headers=headers, ssl=self.client.ssl_context) as response:+ pass++ async def post_data_no_resp(self, url: URL, data: dict):+ async with self.rate_limiter:+ async with self.client_session.post(url, data=data, headers=self.headers, ssl=self.client.ssl_context) as response:+ pass++ async def post(self, url: URL, data: dict):+ async with self.rate_limiter:+ async with self.client_session.post(url, data=data, headers=self.headers, ssl=self.client.ssl_context) as response:+ content = json.loads(await response.content.read())+ return content++ async def exit_handler(self):+ try:+ await self.client_session.close()+ except Exception as e:+ logging.debug(f"Failed to close sqlite database connection: {str(e)}")+++class DownloadSession:+ def __init__(self, client):+ self.client = client+ self.headers = {"user-agent": client.user_agent}+ self.client_session = aiohttp.ClientSession(headers=self.headers, raise_for_status=True,+ cookie_jar=self.client.cookies)+ self.throttle_times = {}++ async def get_filename(self, url: URL, referer: str, current_throttle: int):+ headers = {'Referer': referer, 'user-agent': self.client.user_agent}+ await throttle(self, current_throttle, url.host)+ async with self.client_session.get(url, headers=headers, ssl=self.client.ssl_context,+ raise_for_status=True) as resp:+ filename = resp.content_disposition.filename+ return filename++ async def get_filesize(self, url: URL, referer: str, current_throttle: int):+ headers = {'Referer': referer, 'user-agent': self.client.user_agent}+ await throttle(self, current_throttle, url.host)+ async with self.client_session.get(url, headers=headers, ssl=self.client.ssl_context,+ raise_for_status=True) as resp:+ total_size = int(resp.headers.get('Content-Length', str(0)))+ return total_size++ async def download_file(self, url: URL, referer: str, current_throttle: int, range: str, original_filename: str,+ filename: str, temp_file: str, resume_point: int, show_progress: bool,+ File_Lock: FileLock, folder: Path, title: str):+ headers = {'Referer': referer, 'user-agent': self.client.user_agent}+ if range:+ headers['Range'] = range+ await throttle(self, current_throttle, url.host)+ async with self.client_session.get(url, headers=headers, ssl=self.client.ssl_context,+ raise_for_status=True) as resp:+ content_type = resp.headers.get('Content-Type')+ if 'text' in content_type.lower() or 'html' in content_type.lower():+ logger.debug("Server for %s is either down or the file no longer exists", str(url))+ await File_Lock.remove_lock(original_filename)+ return++ total = int(resp.headers.get('Content-Length', str(0))) + resume_point+ (folder / title).mkdir(parents=True, exist_ok=True)++ with tqdm(total=total, unit_scale=True, unit='B', leave=False, initial=resume_point, desc=filename,+ disable=(not show_progress)) as progress:+ async with aiofiles.open(temp_file, mode='ab') as f:+ async for chunk, _ in resp.content.iter_chunks():+ await asyncio.sleep(0)+ await f.write(chunk)+ progress.update(len(chunk))diff --git a/cyberdrop_dl/utils/downloaders.py b/cyberdrop_dl/client/downloaders.pysimilarity index 65%rename from cyberdrop_dl/utils/downloaders.pyrename to cyberdrop_dl/client/downloaders.pyindex 5a5ad013b..15dd18ec0 100644--- a/cyberdrop_dl/utils/downloaders.py+++ b/cyberdrop_dl/client/downloaders.py@@ -1,6 +1,5 @@import asyncioimport logging-import multiprocessingimport tracebackfrom functools import wrapsfrom pathlib import Path@@ -10,14 +9,14 @@ from random import gaussimport aiofilesimport aiofiles.osimport aiohttp.client_exceptions-from colorama import Forefrom tqdm import tqdmfrom yarl import URL-from .base_functions import FILE_FORMATS, MAX_FILENAME_LENGTH, log, logger, sanitize, ssl_context, user_agent-from .sql_helper import SQLHelper-from .data_classes import AlbumItem, CascadeItem, FileLock-from .rate_limiting import throttle+from ..base_functions.base_functions import FILE_FORMATS, MAX_FILENAME_LENGTH, log, logger, sanitize+from ..base_functions.sql_helper import SQLHelper+from ..base_functions.data_classes import AlbumItem, CascadeItem, FileLock+from ..client.rate_limiting import throttle+from ..client.client import Client, DownloadSessionclass FailureException(Exception):@@ -53,11 +52,11 @@ def retry(f):class Downloader:- def __init__(self, album_obj: AlbumItem, cookie_jar, folder: Path, title: str, attempts: int,- disable_attempt_limit: bool, max_workers: int, exclude_videos: bool, exclude_images: bool,- exclude_audio: bool, exclude_other: bool, SQL_helper: SQLHelper):+ def __init__(self, album_obj: AlbumItem, folder: Path, title: str, attempts: int,+ disable_attempt_limit: bool, max_workers: int, excludes: dict[str, bool], SQL_helper: SQLHelper,+ client: Client):self.album_obj = album_obj- self.cookie_jar = cookie_jar+ self.client = clientself.folder = folderself.title = title@@ -68,32 +67,22 @@ class Downloader:self.current_attempt = {}self.disable_attempt_limit = disable_attempt_limit- self.exclude_videos = exclude_videos- self.exclude_images = exclude_images- self.exclude_audio = exclude_audio- self.exclude_other = exclude_other+ self.excludes = excludesself.max_workers = max_workersself._semaphore = asyncio.Semaphore(max_workers)self.delay = {'cyberfile.is': 1, 'anonfiles.com': 1}- self.throttle_times = {}"""Changed from aiohttp exceptions caught to FailureException to allow for partial downloads."""@retry- async def download_file(- self,- url: URL,- referral: URL,- filename: str,- session: aiohttp.ClientSession,- show_progress: bool = True- ) -> None:+ async def download_file(self, url: URL, referral: URL, filename: str, session: DownloadSession,+ show_progress: bool = True) -> None:"""Download the content of given URL"""if str(url) not in self.current_attempt:self.current_attempt[str(url)] = 0- headers = {'Referer': str(referral), 'user-agent': user_agent}+ referer = str(referral)db_path = url.pathif 'anonfiles' in url.host:@@ -111,39 +100,41 @@ class Downloader:async with self._semaphore:# If ext isn't allowable we likely have an invalid filename, lets go get it.ext = '.' + filename.split('.')[-1].lower()- if not (ext in FILE_FORMATS['Images'] or ext in FILE_FORMATS['Videos'] or ext in FILE_FORMATS['Audio'] or ext in FILE_FORMATS['Other']):+ current_throttle = self.client.throttle+ if not (ext in FILE_FORMATS['Images'] or ext in FILE_FORMATS['Videos'] or+ ext in FILE_FORMATS['Audio'] or ext in FILE_FORMATS['Other']):for key, value in self.delay.items():if key in url.host:- await throttle(self, value, key)- async with session.get(url, headers=headers, ssl=ssl_context, raise_for_status=True) as resp:- try:- filename = resp.content_disposition.filename- filename = await sanitize(filename)- ext = '.' + filename.split('.')[-1].lower()- if not (ext in FILE_FORMATS['Images'] or ext in FILE_FORMATS['Videos'] or ext in FILE_FORMATS['Audio'] or ext in FILE_FORMATS['Other']):- return- except:- await log("\nCouldn't get filename for: " + str(url))+ if value > current_throttle:+ current_throttle = value+ try:+ filename = await session.get_filename(url, referer, current_throttle)+ filename = await sanitize(filename)+ ext = '.' + filename.split('.')[-1].lower()+ if not (ext in FILE_FORMATS['Images'] or ext in FILE_FORMATS['Videos'] or ext in FILE_FORMATS['Audio'] or ext in FILE_FORMATS['Other']):return+ except:+ await log("\nCouldn't get filename for: " + str(url))+ return# Make suffix always lower caseext = '.' + filename.split('.')[-1].lower()filename = filename.replace('.' + filename.split('.')[-1], ext)# Skip based on CLI arg.- if self.exclude_videos:+ if self.excludes['videos']:if ext in FILE_FORMATS['Videos']:logging.debug("Skipping " + filename)return- if self.exclude_images:+ if self.excludes['images']:if ext in FILE_FORMATS['Images']:logging.debug("Skipping " + filename)return- if self.exclude_audio:+ if self.excludes['audio']:if ext in FILE_FORMATS['Audio']:logging.debug("Skipping " + filename)return- if self.exclude_other:+ if self.excludes['other']:if ext in FILE_FORMATS['Other']:logging.debug("Skipping " + filename)return@@ -158,8 +149,7 @@ class Downloader:if complete_file.exists() or partial_file.exists():if complete_file.exists():- async with session.get(url, headers=headers, ssl=ssl_context, raise_for_status=True) as resp:- total_size = int(resp.headers.get('Content-Length', str(0)))+ total_size = session.get_filesize(url, referer, current_throttle)if complete_file.stat().st_size == total_size:await self.SQL_helper.sql_insert_file(db_path, complete_file.name, 1)logger.debug("\nFile already exists and matches expected size: " + str(complete_file))@@ -185,34 +175,19 @@ class Downloader:resume_point = 0temp_file = complete_file.with_suffix(complete_file.suffix + '.part')+ range = Noneif temp_file.exists():resume_point = temp_file.stat().st_size- headers['Range'] = f'bytes={resume_point}-'+ range = f'bytes={resume_point}-'for key, value in self.delay.items():if key in url.host:- await throttle(self, value, key)+ current_throttle = value- async with session.get(url, headers=headers, ssl=ssl_context, raise_for_status=True) as resp:- content_type = resp.headers.get('Content-Type')- if 'text' in content_type.lower() or 'html' in content_type.lower():- logger.debug("Server for %s is either down or the file no longer exists", str(url))- await self.File_Lock.remove_lock(original_filename)- return+ await session.download_file(url, referer, current_throttle, range, original_filename, filename,+ temp_file, resume_point, show_progress, self.File_Lock, self.folder,+ self.title)- total = int(resp.headers.get('Content-Length', str(0))) + resume_point- (self.folder / self.title).mkdir(parents=True, exist_ok=True)-- with tqdm(- total=total, unit_scale=True,- unit='B', leave=False, initial=resume_point,- desc=filename, disable=(not show_progress)- ) as progress:- async with aiofiles.open(temp_file, mode='ab') as f:- async for chunk, _ in resp.content.iter_chunks():- await asyncio.sleep(0)- await f.write(chunk)- progress.update(len(chunk))await self.rename_file(filename, url, db_path)await self.File_Lock.remove_lock(original_filename)@@ -234,7 +209,6 @@ class Downloader:passelse:return- resp.close()except Exception:pass@@ -253,12 +227,7 @@ class Downloader:await self.SQL_helper.sql_update_file(db_path, filename, 1)logger.debug("Finished " + filename)- async def download_and_store(- self,- url_tuple: Tuple,- session: aiohttp.ClientSession,- show_progress: bool = True- ) -> None:+ async def download_and_store(self, url_tuple: Tuple, session: DownloadSession, show_progress: bool = True) -> None:"""Download the content of given URL and store it in a file."""url, referral = url_tuple@@ -276,14 +245,9 @@ class Downloader:show_progress=show_progress)except Exception:logger.debug(traceback.format_exc())- await log(f"\nError attempting {filename}: See downloader.log for details\n", Fore.WHITE)-- async def download_all(- self,- album_obj: AlbumItem,- session: aiohttp.ClientSession,- show_progress: bool = True- ) -> None:+ await log(f"\nError attempting {filename}: See downloader.log for details\n")++ async def download_all(self, album_obj: AlbumItem, session: DownloadSession, show_progress: bool = True) -> None:"""Download the data from all given links and store them into corresponding files."""coros = [self.download_and_store(url_object, session, show_progress)for url_object in album_obj.link_pairs]@@ -292,14 +256,13 @@ class Downloader:async def download_content(self, show_progress: bool = True) -> None:"""Download the content of all links and save them as files."""- async with aiohttp.ClientSession(cookie_jar=self.cookie_jar) as session:- await self.download_all(self.album_obj, session, show_progress=show_progress)+ session = DownloadSession(self.client)+ await self.download_all(self.album_obj, session, show_progress=show_progress)self.SQL_helper.conn.commit()-async def get_downloaders(Cascade: CascadeItem, folder: Path, attempts: int, disable_attempt_limit: bool, threads: int,- exclude_videos: bool, exclude_images: bool, exclude_audio: bool, exclude_other: bool,- SQL_helper: SQLHelper) -> List[Downloader]:+async def get_downloaders(Cascade: CascadeItem, folder: Path, attempts: int, disable_attempt_limit: bool,+ max_workers: int, excludes: dict[str, bool], SQL_helper: SQLHelper, client: Client) -> List[Downloader]:"""Get a list of downloaders for each supported type of URLs.We shouldn't just assume that each URL will have the same netloc asthe first one, so we need to classify them one by one, sort them to@@ -309,17 +272,12 @@ async def get_downloaders(Cascade: CascadeItem, folder: Path, attempts: int, disdownloaders = []- cookie_jar = Cascade.cookies-for domain, domain_obj in Cascade.domains.items():- max_workers = threads if threads != 0 else multiprocessing.cpu_count()if 'bunkr' in domain or 'pixeldrain' in domain or 'anonfiles' in domain:max_workers = 2 if (max_workers > 2) else max_workersfor title, album_obj in domain_obj.albums.items():- downloader = Downloader(album_obj, cookie_jar=cookie_jar, title=title, folder=folder,- attempts=attempts, disable_attempt_limit=disable_attempt_limit,- max_workers=max_workers, exclude_videos=exclude_videos,- exclude_images=exclude_images, exclude_audio=exclude_audio,- exclude_other=exclude_other, SQL_helper=SQL_helper)+ downloader = Downloader(album_obj, title=title, folder=folder, attempts=attempts,+ disable_attempt_limit=disable_attempt_limit, max_workers=max_workers,+ excludes=excludes, SQL_helper=SQL_helper, client=client)downloaders.append(downloader)return downloadersdiff --git a/cyberdrop_dl/utils/rate_limiting.py b/cyberdrop_dl/client/rate_limiting.pysimilarity index 96%rename from cyberdrop_dl/utils/rate_limiting.pyrename to cyberdrop_dl/client/rate_limiting.pyindex 9afa53453..3352a65d8 100644--- a/cyberdrop_dl/utils/rate_limiting.py+++ b/cyberdrop_dl/client/rate_limiting.py@@ -6,7 +6,7 @@ from datetime import datetimefrom types import TracebackTypefrom typing import Optional, Callable, Awaitable, Any, Type-from .base_functions import logger+from cyberdrop_dl.base_functions.base_functions import loggerclass AsyncRateLimiter:@@ -67,7 +67,7 @@ class AsyncRateLimiter:async def throttle(self, delay, host) -> None:- if delay is None:+ if delay is None or delay == 0:returnkey: Optional[str] = Nonediff --git a/cyberdrop_dl/crawlers/Anonfiles_Spider.py b/cyberdrop_dl/crawlers/Anonfiles_Spider.pynew file mode 100644index 000000000..c09a447a4--- /dev/null+++ b/cyberdrop_dl/crawlers/Anonfiles_Spider.py@@ -0,0 +1,32 @@+from yarl import URL++from ..base_functions.base_functions import log, logger+from ..base_functions.data_classes import DomainItem+from ..client.client import Session+++class AnonfilesCrawler:+ def __init__(self, *, include_id=False):+ self.include_id = include_id++ async def fetch(self, session: Session, url: URL):+ domain_obj = DomainItem(url.host, {})++ await log("Starting scrape of " + str(url))++ try:+ soup = await session.get_BS4(url)++ title = "Anonfiles"+ link = soup.select_one("a[id=download-url]")+ link = URL(link.get('href'))+ await domain_obj.add_to_album(title, link, url)++ except Exception as e:+ logger.debug("Error encountered while handling %s", str(url), exc_info=True)+ await log("Error scraping " + str(url))+ logger.debug(e)++ await log("Finished scrape of " + str(url))++ return domain_objdiff --git a/cyberdrop_dl/crawlers/Bunkr_Spider.py b/cyberdrop_dl/crawlers/Bunkr_Spider.pynew file mode 100644index 000000000..0bd3277b2--- /dev/null+++ b/cyberdrop_dl/crawlers/Bunkr_Spider.py@@ -0,0 +1,71 @@+import json++from yarl import URL++from ..base_functions.base_functions import log, logger, make_title_safe, check_direct, FILE_FORMATS+from ..base_functions.data_classes import DomainItem+from ..client.client import Session+++class BunkrCrawler:+ def __init__(self, *, include_id=False):+ self.include_id = include_id++ async def fetch(self, session: Session, url: URL):+ domain_obj = DomainItem(url.host, {})++ if await check_direct(url):+ ext = '.' + str(url).split('.')[-1]+ if ext in FILE_FORMATS['Videos']:+ url = URL(str(url).replace('https://cdn', 'https://media-files'))+ await domain_obj.add_to_album(link=url, referral=url, title="Bunkr Loose Files")+ return domain_obj++ if "stream.bunkr." in url.host:+ link = await self.stream(session, url)+ await domain_obj.add_to_album(link=link, referral=url, title="Bunkr Loose Files")+ await log("Finished scrape of " + str(url))+ return domain_obj++ await log("Starting scrape of " + str(url))++ try:+ soup = await session.get_BS4(url)+ build_id = json.loads(soup.select_one("script[id=__NEXT_DATA__]").get_text())++ json_fetch = URL("https://" + url.host + "/_next/data/" + build_id['buildId'] + url.path + '.json')+ text = await session.get_text(json_fetch)+ json_obj = json.loads(text)['pageProps']+ title = await make_title_safe(json_obj['album']['name'])+ for file in json_obj['files']:+ ext = '.' + file['name'].split('.')[-1].lower()+ if ext in FILE_FORMATS['Videos']:+ cdn_loc = file['cdn']+ media_loc = cdn_loc.replace('cdn', 'media-files')+ link = URL(media_loc + '/' + file['name'])+ else:+ link = URL(file['cdn'] + '/' + file['name'])+ await domain_obj.add_to_album(title, link, url)++ except Exception as e:+ logger.debug("Error encountered while handling %s", str(url), exc_info=True)+ await log("Error scraping " + str(url))+ logger.debug(e)++ await log("Finished scrape of " + str(url))++ return domain_obj++ async def stream(self, session: Session, url: URL):+ try:+ soup = await session.get_BS4(url)+ json_obj = json.loads(soup.select_one("script[id=__NEXT_DATA__]").text)+ if not json_obj['props']['pageProps']:+ raise Exception("Couldn't get link from HTML")+ link = URL(json_obj['props']['pageProps']['file']['mediafiles'] + '/' + json_obj['props']['pageProps']['file']['name'])+ return link++ except Exception as e:+ logger.debug("Error encountered while handling %s", str(url), exc_info=True)+ await log("Error scraping " + str(url))+ logger.debug(e)diff --git a/cyberdrop_dl/crawlers/Coomer_Spider.py b/cyberdrop_dl/crawlers/Coomer_Spider.pynew file mode 100644index 000000000..ca9e6377e--- /dev/null+++ b/cyberdrop_dl/crawlers/Coomer_Spider.py@@ -0,0 +1,82 @@+from yarl import URL++from ..base_functions.base_functions import log, logger, make_title_safe+from ..base_functions.data_classes import DomainItem+from ..client.client import Session+++class CoomerCrawler:+ def __init__(self, *, include_id=False):+ self.include_id = include_id++ async def fetch(self, session: Session, url: URL):+ await log("Starting scrape of " + str(url))+ domain_obj = DomainItem('coomer.party', {})+ results = []++ if "thumbnail" in url.parts:+ parts = [x for x in url.parts if x not in ("thumbnail", "/")]+ link = URL("https://coomer.party/" + "/".join(parts))+ await domain_obj.add_to_album("Loose Coomer.Party Files", link, link)+ elif "data" in url.parts:+ await domain_obj.add_to_album("Loose Coomer.Party Files", url, url)+ else:+ results.extend(await self.parse_profile(session, url))++ for result in results:+ await domain_obj.add_to_album(result[0], result[1], result[2])++ await log("Finished scrape of " + str(url))+ return domain_obj++ async def parse_profile(self, session: Session, url: URL):+ try:+ soup = await session.get_BS4(url)+ title = soup.select_one("span[itemprop=name]").get_text()+ title = title + " (Coomer.party)"+ results = []++ posts = soup.select("a[class=fancy-link]")+ for post in posts:+ path = post.get('href')+ if path:+ post_link = URL("https://coomer.party" + path)+ results.extend(await self.parse_post(session, post_link, title))++ next_page = soup.select_one('a[title="Next page"]')+ if next_page:+ next_page = next_page.get('href')+ if next_page:+ results.extend(await self.parse_profile(session, URL("https://coomer.party" + next_page)))+ return results++ except Exception as e:+ logger.debug("Error encountered while handling %s", str(url), exc_info=True)+ await log("Error scraping " + str(url))+ logger.debug(e)+ return []++ async def parse_post(self, session: Session, url: URL, title: str):+ try:+ soup = await session.get_BS4(url)+ results = []++ title = title + '/' + await make_title_safe(soup.select_one("h1[class=post__title]").text.replace('\n', '').replace("..", ""))++ images = soup.select('a[class="fileThumb"]')+ for image in images:+ image_link = URL("https://coomer.party" + image.get('href'))+ results.append([title, image_link, url])++ downloads = soup.select('a[class=post__attachment-link]')+ for download in downloads:+ download_link = URL("https://coomer.party" + download.get('href'))+ results.append([title, download_link, url])++ return results++ except Exception as e:+ logger.debug("Error encountered while handling %s", str(url), exc_info=True)+ await log("Error scraping " + str(url))+ logger.debug(e)+ return []diff --git a/cyberdrop_dl/crawlers/Cyberdrop_Spider.py b/cyberdrop_dl/crawlers/Cyberdrop_Spider.pynew file mode 100644index 000000000..150fa456a--- /dev/null+++ b/cyberdrop_dl/crawlers/Cyberdrop_Spider.py@@ -0,0 +1,46 @@+from yarl import URL++from ..base_functions.base_functions import log, logger, make_title_safe, check_direct+from ..base_functions.data_classes import DomainItem+from ..client.client import Session+++class CyberdropCrawler:+ def __init__(self, *, include_id=False):+ self.include_id = include_id++ async def fetch(self, session: Session, url: URL):+ domain_obj = DomainItem(url.host, {})++ if await check_direct(url):+ link = URL(url)+ await domain_obj.add_to_album(link=link, referral=url, title="Cyberdrop Loose Files")+ return domain_obj++ await log("Starting scrape of " + str(url))++ try:+ soup = await session.get_BS4(url)++ title = soup.select_one("h1[id=title]").get_text()+ if title is None:+ title = url.name+ elif self.include_id:+ titlep2 = url.name+ titlep2 = [s for s in titlep2 if "." in s][-1]+ title = title + " - " + titlep2+ title = await make_title_safe(title.replace(r"\n", "").strip())++ links = soup.select('div[class="image-container column"] a')+ for link in links:+ link = URL(link.get('href'))+ await domain_obj.add_to_album(title, link, url)++ except Exception as e:+ logger.debug("Error encountered while handling %s", str(url), exc_info=True)+ await log("Error scraping " + str(url))+ logger.debug(e)++ await log("Finished scrape of " + str(url))++ return domain_objdiff --git a/cyberdrop_dl/crawlers/Cyberfile_Spider.py b/cyberdrop_dl/crawlers/Cyberfile_Spider.pynew file mode 100644index 000000000..b7917a782--- /dev/null+++ b/cyberdrop_dl/crawlers/Cyberfile_Spider.py@@ -0,0 +1,197 @@+from bs4 import BeautifulSoup+from yarl import URL++from ..base_functions.base_functions import log, logger+from ..base_functions.data_classes import DomainItem+from ..client.client import Session+++class CyberfileCrawler:+ def __init__(self):+ self.load_files = URL('https://cyberfile.is/account/ajax/load_files')+ self.file_details = URL('https://cyberfile.is/account/ajax/file_details')++ async def fetch(self, session: Session, url: URL):+ await log("Starting scrape of " + str(url))+ domain_obj = DomainItem("cyberfile.is", {})+ download_links = []+ if 'folder' in url.parts:+ nodeId = await self.folder_nodeId(session, url)+ contentIds = await self.folder_content(session, url, nodeId, 1)+ download_links = await self.get_download_links(session, url, contentIds)+ elif 'shared' in url.parts:+ nodeIds, contentIds = await self.shared_nodeId_root_content(session, url, 1)+ for title, nodeId in nodeIds:+ contentIds.extend(await self.shared_content(session, url, nodeId, 1, title))+ download_links = await self.get_download_links(session, url, contentIds)+ else:+ contentId = await self.get_single_contentId(session, url)+ if contentId:+ download_links = await self.get_download_links(session, url, [("Loose Cyberfile Files", contentId)])+ for title, download_link in download_links:+ await domain_obj.add_to_album(title, download_link, url)+ await log("Finished scrape of " + str(url))+ return domain_obj++ async def folder_nodeId(self, session: Session, url: URL):+ try:+ soup = await session.get_BS4(url)+ script_func = soup.select_one('div[class="page-container horizontal-menu with-sidebar fit-logo-with-sidebar logged-out clear-adblock"] script').text+ script_func = script_func.split('loadImages(')[-1]+ script_func = script_func.split(';')[0]+ nodeId = int(script_func.split(',')[1].replace("'", ""))+ return nodeId++ except Exception as e:+ await log("Error scraping " + str(url))+ logger.debug(e)+ return 0++ async def get_single_contentId(self, session: Session, url: URL):+ try:+ soup = await session.get_BS4(url)+ script_funcs = soup.select('script')+ for script in script_funcs:+ script_text = script.text+ if script_text:+ if "showFileInformation" in script_text:+ parta = script_text.split("showFileInformation(")+ parta = [x for x in parta if x[0].isdigit()][0]+ partb = parta.split(");")[0]+ contentId = int(partb)+ return contentId+ return None++ except Exception as e:+ await log("Error scraping " + str(url))+ logger.debug(e)+ return 0++ async def shared_nodeId_root_content(self, session: Session, url: URL, page):+ try:+ # Initial page load to tell server, this is what we want.+ await session.post_no_resp(url, {'referer': str(url), "user-agent": session.client.user_agent})++ # get the content listings+ data = {"pageType": "nonaccountshared", "nodeId": '', "pageStart": page, "perPage": 0, "filterOrderBy": ""}+ nodes = []+ contents = []++ content = await session.post(self.load_files, data)+ text = content['html']+ title = content['page_title']+ soup = BeautifulSoup(text.replace("\\", ""), 'html.parser')+ total_pages = int(soup.select_one('input[id=rspTotalPages]').get('value'))+ listings = soup.select("div[class=fileListing] div")+ for listing in listings:+ title = content['page_title']+ try:+ title = title + '/' + listing.select_one('span[class=filename]').text+ nodes.append((title, int(listing.get('folderid'))))+ except (TypeError, AttributeError):+ pass+ try:+ contents.append((title, int(listing.get('fileid'))))+ except TypeError:+ pass++ if page < total_pages:+ nodes_temp, content_temp = await self.shared_nodeId_root_content(session, url, page+1)+ nodes.extend(nodes_temp)+ contents.extend(content_temp)+ return nodes, contents++ except Exception as e:+ await log("Error scraping " + str(url))+ logger.debug(e)+ return []++ async def shared_content(self, session, url: URL, nodeId, page, title=None):+ try:+ nodes = []+ contents = []+ data = {"pageType": "nonaccountshared", "nodeId": nodeId, "pageStart": page, "perPage": 0, "filterOrderBy": ""}++ content = await session.post(self.load_files, data)+ text = content['html']+ title = title if title else content['page_title']+ soup = BeautifulSoup(text.replace("\\", ""), 'html.parser')+ total_pages = int(soup.select_one('input[id=rspTotalPages]').get('value'))+ listings = soup.select("div[class=fileListing] div")+ for listing in listings:+ try:+ nodes.append(int(listing.get('folderid')))+ except TypeError:+ pass+ try:+ contents.append((title, int(listing.get('fileid'))))+ except TypeError:+ pass++ if page < total_pages:+ contents.extend(await self.shared_content(session, url, nodeId, page+1, title))+ for node in nodes:+ contents.extend(await self.shared_content(session, url, node, 1, title))+ return contents++ except Exception as e:+ await log("Error scraping " + str(url))+ logger.debug(e)+ return []++ async def folder_content(self, session, url: URL, nodeId, page):+ data = {"pageType": "folder", "nodeId": nodeId, "pageStart": page, "perPage": 0, "filterOrderBy": ""}+ nodes = []+ contents = []+ try:+ content = await session.post(self.load_files, data)+ text = content['html']+ title = content['page_title']+ soup = BeautifulSoup(text.replace("\\", ""), 'html.parser')+ total_pages = int(soup.select_one('input[id=rspTotalPages]').get('value'))+ listings = soup.select("div[class=fileListing] div")+ for listing in listings:+ try:+ nodes.append(int(listing.get('folderid')))+ except TypeError:+ pass+ try:+ contents.append((title, int(listing.get('fileid'))))+ except TypeError:+ pass++ if page < total_pages:+ contents.extend(await self.folder_content(session, url, nodeId, page+1))+ for node in nodes:+ contents.extend(await self.folder_content(session, url, node, 1))+ return contents++ except Exception as e:+ await log("Error scraping " + str(url))+ logger.debug(e)+ return []++ async def get_download_links(self, session, url, contentIds):+ download_links = []+ try:+ for title, contentId in contentIds:+ data = {"u": contentId}+ content = await session.post(self.file_details, data)+ text = content['html']+ soup = BeautifulSoup(text.replace("\\", ""), 'html.parser')+ menu = soup.select_one('ul[class="dropdown-menu dropdown-info account-dropdown-resize-menu"] li a')+ button = soup.select_one('div[class="btn-group responsiveMobileMargin"] button')+ if menu:+ html_download_text = menu.get("onclick")+ link = URL(html_download_text.replace("openUrl('", "").replace("'); return false;", ""))+ download_links.append((title, link))+ elif button:+ html_download_text = button.get("onclick")+ link = URL(html_download_text.replace("openUrl('", "").replace("'); return false;", ""))+ download_links.append((title, link))+ return download_links++ except Exception as e:+ await log("Error scraping " + str(url))+ logger.debug(e)+ return []diff --git a/cyberdrop_dl/crawlers/Erome_Spider.py b/cyberdrop_dl/crawlers/Erome_Spider.pynew file mode 100644index 000000000..a44e17ebe--- /dev/null+++ b/cyberdrop_dl/crawlers/Erome_Spider.py@@ -0,0 +1,41 @@+from yarl import URL++from ..base_functions.base_functions import log, logger, make_title_safe+from ..base_functions.data_classes import DomainItem+from ..client.client import Session+++class EromeCrawler():+ def __init__(self, *, include_id=False):+ self.include_id = include_id++ async def fetch(self, session: Session, url: URL):+ domain_obj = DomainItem(url.host, {})++ await log("Starting scrape of " + str(url))++ try:+ soup = await session.get_BS4(url)+ title = soup.select_one('div[class="col-sm-12 page-content"] h1').get_text()+ if title is None:+ title = url.name+ elif self.include_id:+ title = title + " - " + url.name+ title = await make_title_safe(title)++ # Images+ for link in soup.select('img[class="img-front lasyload"]'):+ await domain_obj.add_to_album(title, URL(link['data-src']), url)++ # Videos+ for link in soup.select('div[class=media-group] div[class=video-lg] video source'):+ await domain_obj.add_to_album(title, URL(link['src']), url)++ except Exception as e:+ logger.debug("Error encountered while handling %s", str(url), exc_info=True)+ await log("Error scraping " + str(url))+ logger.debug(e)++ await log("Finished scrape of " + str(url))++ return domain_objdiff --git a/cyberdrop_dl/crawlers/Gfycat_Spider.py b/cyberdrop_dl/crawlers/Gfycat_Spider.pynew file mode 100644index 000000000..2785ffed3--- /dev/null+++ b/cyberdrop_dl/crawlers/Gfycat_Spider.py@@ -0,0 +1,29 @@+from yarl import URL++from ..base_functions.base_functions import log, logger+from ..client.client import Session+++class GfycatCrawler:+ async def fetch(self, session: Session, url: URL):+ try:+ soup = await session.get_BS4(url)++ video = soup.select_one("video[class='video media']")+ video_srcs = video.select("source")++ # Find the biggest video source, usually the host is giant.gyfcat+ video_link = None+ for src in video_srcs:+ link = URL(src.get("src"))+ if str(link.host).find("giant") != -1:+ video_link = link+ if video_link is None:+ video_link = URL(video_srcs[0].get("src"))++ return video_link++ except Exception as e:+ logger.debug("Error encountered while handling %s", str(url), exc_info=True)+ await log("Error scraping " + str(url))+ logger.debug(e)diff --git a/cyberdrop_dl/utils/crawlers/GoFile_Spider.py b/cyberdrop_dl/crawlers/GoFile_Spider.pysimilarity index 78%rename from cyberdrop_dl/utils/crawlers/GoFile_Spider.pyrename to cyberdrop_dl/crawlers/GoFile_Spider.pyindex 287b024b3..eed9ae3cb 100644--- a/cyberdrop_dl/utils/crawlers/GoFile_Spider.py+++ b/cyberdrop_dl/crawlers/GoFile_Spider.py@@ -1,19 +1,19 @@import httpfrom typing import Union-from colorama import Forefrom gofile import Gofilefrom yarl import URL-from ..base_functions import log-from ..data_classes import DomainItem+from ..base_functions.base_functions import log+from ..base_functions.data_classes import DomainItem+from ..client.client import Sessionclass GofileCrawler():def __init__(self):self.client = Gofile()- async def fetch(self, session, url):+ async def fetch(self, session: Session, url: URL):domain_obj = DomainItem('gofile.io', {})# Set cookie in cookie_jar@@ -21,21 +21,21 @@ class GofileCrawler():morsel = http.cookies.Morsel()morsel['domain'] = 'gofile.io'morsel.set('accountToken', client_token, client_token)- session.cookie_jar.update_cookies({'gofile.io': morsel})+ session.client_session.cookie_jar.update_cookies({'gofile.io': morsel})results = await self.get_links(url)- await log("Starting scrape of " + str(url), Fore.WHITE)+ await log("Starting scrape of " + str(url))if results:for result in results:await domain_obj.add_to_album(result['title'], result['url'], result['referral'])- await log("Finished scrape of " + str(url), Fore.WHITE)+ await log("Finished scrape of " + str(url))return domain_obj- async def get_links(self, url, og_title=None):+ async def get_links(self, url: URL, og_title=None):results = []content_id = url.name if url.host == 'gofile.io' else urltry:diff --git a/cyberdrop_dl/crawlers/Kemono_Spider.py b/cyberdrop_dl/crawlers/Kemono_Spider.pynew file mode 100644index 000000000..105649697--- /dev/null+++ b/cyberdrop_dl/crawlers/Kemono_Spider.py@@ -0,0 +1,82 @@+from yarl import URL++from ..base_functions.base_functions import log, logger, make_title_safe+from ..base_functions.data_classes import DomainItem+from ..client.client import Session+++class KemonoCrawler:+ def __init__(self, *, include_id=False):+ self.include_id = include_id++ async def fetch(self, session: Session, url: URL):+ await log("Starting scrape of " + str(url))+ domain_obj = DomainItem('kemono.party', {})+ results = []++ if "thumbnail" in url.parts:+ parts = [x for x in url.parts if x not in ("thumbnail", "/")]+ link = URL("https://kemono.party/" + "/".join(parts))+ await domain_obj.add_to_album("Loose Kemono.Party Files", link, link)+ elif "data" in url.parts:+ await domain_obj.add_to_album("Loose Kemono.Party Files", url, url)+ else:+ results.extend(await self.parse_profile(session, url))++ for result in results:+ await domain_obj.add_to_album(result[0], result[1], result[2])++ await log("Finished scrape of " + str(url))+ return domain_obj++ async def parse_profile(self, session: Session, url: URL):+ try:+ soup = await session.get_BS4(url)+ title = soup.select_one("span[itemprop=name]").get_text()+ title = title + " (Kemono.party)"+ results = []++ posts = soup.select("a[class=fancy-link]")+ for post in posts:+ path = post.get('href')+ if path:+ post_link = URL("https://kemono.party" + path)+ results.extend(await self.parse_post(session, post_link, title))++ next_page = soup.select_one('a[title="Next page"]')+ if next_page:+ next_page = next_page.get('href')+ if next_page:+ results.extend(await self.parse_profile(session, URL("https://kemono.party" + next_page)))+ return results++ except Exception as e:+ logger.debug("Error encountered while handling %s", str(url), exc_info=True)+ await log("Error scraping " + str(url))+ logger.debug(e)+ return []++ async def parse_post(self, session: Session, url: URL, title: str):+ try:+ soup = await session.get_BS4(url)+ results = []++ title = title + '/' + await make_title_safe(soup.select_one("h1[class=post__title]").text.replace('\n', '').replace("..", ""))++ images = soup.select('a[class="fileThumb"]')+ for image in images:+ image_link = URL("https://kemono.party" + image.get('href'))+ results.append([title, image_link, url])++ downloads = soup.select('a[class=post__attachment-link]')+ for download in downloads:+ download_link = URL("https://kemono.party" + download.get('href'))+ results.append([title, download_link, url])++ return results++ except Exception as e:+ logger.debug("Error encountered while handling %s", str(url), exc_info=True)+ await log("Error scraping " + str(url))+ logger.debug(e)+ return []diff --git a/cyberdrop_dl/utils/crawlers/Pixeldrain_Crawler.py b/cyberdrop_dl/crawlers/Pixeldrain_Crawler.pysimilarity index 58%rename from cyberdrop_dl/utils/crawlers/Pixeldrain_Crawler.pyrename to cyberdrop_dl/crawlers/Pixeldrain_Crawler.pyindex dcfcce503..ae459e6d4 100644--- a/cyberdrop_dl/utils/crawlers/Pixeldrain_Crawler.py+++ b/cyberdrop_dl/crawlers/Pixeldrain_Crawler.py@@ -1,35 +1,16 @@-import json--from colorama import Forefrom yarl import URL-from ..base_functions import log, ssl_context, user_agent, logger-from ..data_classes import DomainItem+from ..base_functions.base_functions import log, logger+from ..base_functions.data_classes import DomainItem+from ..client.client import Sessionclass PixelDrainCrawler:def __init__(self):self.api = URL('https://pixeldrain.com/api/')- async def create_download_link(self, file):- final_url = (URL('https://pixeldrain.com/api/file/') / file).with_query('download')- return final_url-- async def get_listings(self, session, identifier, url):- links = []- try:- async with session.get(self.api / "list" / identifier, headers={"user-agent": user_agent}, ssl=ssl_context) as response:- content = json.loads(await response.content.read())- for file in content['files']:- links.append(await self.create_download_link(file['id']))- return links- except Exception as e:- await log("Error scraping " + str(url))- logger.debug(e)- return None-- async def fetch(self, session, url):- await log("Starting scrape of " + str(url), Fore.WHITE)+ async def fetch(self, session: Session, url: URL):+ await log("Starting scrape of " + str(url))domain_obj = DomainItem("pixeldrain.com", {})identifier = str(url).split('/')[-1]@@ -42,5 +23,21 @@ class PixelDrainCrawler:link = await self.create_download_link(identifier)await domain_obj.add_to_album("Loose Pixeldrain Files", link, url)- await log("Finished scrape of " + str(url), Fore.WHITE)+ await log("Finished scrape of " + str(url))return domain_obj++ async def get_listings(self, session: Session, identifier: str, url: URL):+ links = []+ try:+ content = await session.get_json((self.api / "list" / identifier))+ for file in content['files']:+ links.append(await self.create_download_link(file['id']))+ return links+ except Exception as e:+ await log("Error scraping " + str(url))+ logger.debug(e)+ return None++ async def create_download_link(self, file):+ final_url = (URL('https://pixeldrain.com/api/file/') / file).with_query('download')+ return final_urldiff --git a/cyberdrop_dl/crawlers/Redgifs_Spider.py b/cyberdrop_dl/crawlers/Redgifs_Spider.pynew file mode 100644index 000000000..b72dab7d0--- /dev/null+++ b/cyberdrop_dl/crawlers/Redgifs_Spider.py@@ -0,0 +1,29 @@+from yarl import URL++from cyberdrop_dl.base_functions.base_functions import log, logger+from ..client.client import Session+++class RedGifsCrawler:+ async def fetch(self, session: Session, url: URL):+ try:+ soup = await session.get_BS4(url)+ video_metas = soup.select("meta[property='og:video']")++ # Find the video that doesn't contain "mobile"+ video_src = None+ for video_meta in video_metas:+ link = video_meta.get("content")+ if "mobile" not in link:+ video_src = URL(link)++ # Just get the first one if we didn't find the non-mobile+ if video_src is None and len(video_metas) != 0:+ video_src = URL(video_metas[0].get("content"))++ return video_src++ except Exception as e:+ logger.debug("Error encountered while handling %s", str(url), exc_info=True)+ await log("Error scraping " + str(url))+ logger.debug(e)diff --git a/cyberdrop_dl/crawlers/Saint_Spider.py b/cyberdrop_dl/crawlers/Saint_Spider.pynew file mode 100644index 000000000..97abc0110--- /dev/null+++ b/cyberdrop_dl/crawlers/Saint_Spider.py@@ -0,0 +1,28 @@+from yarl import URL++from ..base_functions.base_functions import log, logger+from ..base_functions.data_classes import DomainItem+from ..client.client import Session+++class SaintCrawler:+ def __init__(self, *, include_id=False):+ self.include_id = include_id++ async def fetch(self, session: Session, url: URL):+ domain_obj = DomainItem(url.host, {})+ await log("Starting scrape of " + str(url))++ try:+ soup = await session.get_BS4(url)+ link = URL(soup.select_one('video[id=main-video] source').get('src'))+ await domain_obj.add_to_album("Saint Loose Files", link, url)++ except Exception as e:+ logger.debug("Error encountered while handling %s", str(url), exc_info=True)+ await log("Error scraping " + str(url))+ logger.debug(e)++ await log("Finished scrape of " + str(url))++ return domain_objdiff --git a/cyberdrop_dl/crawlers/ShareX_Spider.py b/cyberdrop_dl/crawlers/ShareX_Spider.pynew file mode 100644index 000000000..596bba228--- /dev/null+++ b/cyberdrop_dl/crawlers/ShareX_Spider.py@@ -0,0 +1,155 @@+import asyncio++from yarl import URL++from ..base_functions.base_functions import log, logger, make_title_safe, check_direct+from ..base_functions.data_classes import DomainItem+from ..client.client import Session+++class ShareXCrawler:+ def __init__(self, *, include_id=False):+ self.include_id = include_id++ async def fetch(self, session: Session, url: URL):+ domain_obj = DomainItem(url.host, {})++ await log("Starting scrape of " + str(url))++ if await check_direct(url):+ url = url.with_name(url.name.replace('.md.', '.').replace('.th.', '.'))+ await domain_obj.add_to_album(link=url, referral=url, title="ShareX Loose Files")+ return domain_obj++ if "album" in url.parts or "a" in url.parts:+ results = await self.parse(session, url)+ elif "albums" in url.parts:+ results = await self.get_albums(session, url)+ elif 'image' in url.parts or 'img' in url.parts or 'images' in url.parts:+ results = await self.get_singular(session, url)+ else:+ results = await self.parse_profile(session, url)++ for result in results:+ await domain_obj.add_to_album(result['title'], result['url'], result['referral'])++ await log("Finished scrape of " + str(url))++ return domain_obj++ async def get_albums(self, session: Session, url: URL):+ results = []+ try:+ soup = await session.get_BS4(url)+ albums = soup.select("a[class='image-container --media']")+ for album in albums:+ album_url = URL(album.get('href'))+ results.extend(result for result in await self.parse(session, album_url))+ except Exception as e:+ logger.debug("Error encountered while handling %s", str(url), exc_info=True)+ await log("Error scraping " + str(url))+ logger.debug(e)+ return results++ async def get_singular(self, session: Session, url: URL):+ results = []+ await asyncio.sleep(1)+ try:+ soup = await session.get_BS4(url)+ link = URL(soup.select_one("input[id=embed-code-2]").get('value'))+ link = link.with_name(link.name.replace('.md.', '.').replace('.th.', '.'))+ title = "ShareX Loose Files"+ results.append({'url': link, 'title': title, 'referral': url, 'cookies': ''})+ except Exception as e:+ logger.debug("Error encountered while handling %s", str(url), exc_info=True)+ await log("Error scraping " + str(url))+ logger.debug(e)+ return results++ async def get_sub_album_links(self, session: Session, url: URL, og_title: str):+ results = []+ try:+ soup = await session.get_BS4(url)+ albums = soup.select("div[class=pad-content-listing] div")+ for album in albums:+ album_url = album.get('data-url-short')+ if album_url is not None:+ album_url = URL(album_url)+ results.extend(result for result in await self.parse(session, album_url, og_title=og_title))+ except Exception as e:+ logger.debug("Error encountered while handling %s", str(url), exc_info=True)+ await log("Error scraping " + str(url))+ logger.debug(e)+ return results++ async def parse_profile(self, session: Session, url: URL):+ results = []+ try:+ soup = await session.get_BS4(url)+ title = soup.select_one("div[class=header] h1 strong").get_text()+ if title is None:+ title = url.name+ elif self.include_id:+ titlep2 = url.name+ title = title + " - " + titlep2+ title = await make_title_safe(title.replace(r"\n", "").strip())++ list_recent = URL(soup.select_one("a[id=list-most-recent-link]").get('href'))+ results.extend(result for result in await self.get_list_links(session, list_recent, title))+ except Exception as e:+ logger.debug("Error encountered while handling %s", str(url), exc_info=True)+ await log("Error scraping " + str(url))+ logger.debug(e)+ return results++ async def get_list_links(self, session: Session, url: URL, title: str):+ results = []+ try:+ soup = await session.get_BS4(url)+ if url.host == 'jpg.church':+ links = soup.select("a[href*=img] img")+ else:+ links = soup.select("a[href*=image] img")+ for link in links:+ link = URL(link.get('src'))+ link = link.with_name(link.name.replace('.md.', '.').replace('.th.', '.'))+ results.append({'url': link, 'title': title, 'referral': url, 'cookies': ''})+ next_page = soup.select_one('li.pagination-next a')+ if next_page is not None:+ next_page = next_page.get('href')+ if next_page is not None:+ next_page = URL(next_page)+ results.extend(result for result in await self.get_list_links(session, next_page, title))+ except Exception as e:+ logger.debug("Error encountered while handling %s", str(url), exc_info=True)+ await log("Error scraping " + str(url))+ logger.debug(e)+ return results++ async def parse(self, session: Session, url: URL, og_title=None):+ results = []+ try:+ soup = await session.get_BS4(url)++ title = soup.select_one("a[data-text=album-name]").get_text()+ if title is None:+ title = url.name+ elif self.include_id:+ titlep2 = url.name+ title = title + " - " + titlep2+ title = await make_title_safe(title.replace(r"\n", "").strip())++ if og_title is not None:+ title = og_title + "/" + title++ sub_albums = URL(soup.select_one("a[id=tab-sub-link]").get("href"))+ results.extend(result for result in await self.get_sub_album_links(session, sub_albums, title))++ list_recent = URL(soup.select_one("a[id=list-most-recent-link]").get("href"))+ results.extend(result for result in await self.get_list_links(session, list_recent, title))++ except Exception as e:+ logger.debug("Error encountered while handling %s", str(url), exc_info=True)+ await log("Error scraping " + str(url))+ logger.debug(e)+ return resultsdiff --git a/cyberdrop_dl/crawlers/Thotsbay_Spider.py b/cyberdrop_dl/crawlers/Thotsbay_Spider.pynew file mode 100644index 000000000..6f069a2d9--- /dev/null+++ b/cyberdrop_dl/crawlers/Thotsbay_Spider.py@@ -0,0 +1,206 @@+import asyncio+import re++from bs4 import BeautifulSoup+from yarl import URL++from ..base_functions.base_functions import log, logger, make_title_safe+from ..base_functions.data_classes import AuthData, CascadeItem+from ..client.client import Session+++class ThotsbayCrawler:+ def __init__(self, *, include_id=False, auth: AuthData = None, scraping_mapper, separate_posts=False):+ self.include_id = include_id+ self.separate_posts = separate_posts+ self.username, self.password = (auth.username, auth.password) if auth else (None, None)+ self.scraping_mapper = scraping_mapper+ self.lock = 0++ async def login(self, session: Session, url: URL):+ domain = URL("https://" + url.host) / "login"+ text = await session.get_text(domain)+ if "You are already logged in" in text:+ return+ soup = BeautifulSoup(text, 'html.parser')++ inputs = soup.select('form input')+ data = {+ elem['name']: elem['value']+ for elem in inputs+ if elem.get('name') and elem.get('value')+ }+ data.update({"login": self.username, "password": self.password, "_xfRedirect": str(domain)})+ return await session.post_data_no_resp(domain/"login", data=data)++ async def fetch(self, session: Session, url: URL):+ await log("Starting scrape of " + str(url))+ cascade = CascadeItem({})++ try:+ if self.username and self.password:+ while True:+ if self.lock == 0:+ self.lock = 1+ await self.login(session, url)+ self.lock = 0+ break+ await asyncio.sleep(2)+ else:+ await log("login wasn't provided, consider using --thotsbay-username and --thotsbay-password")+ await log("Not being logged in might cause issues.")+ await self.parse_thread(session, url, cascade, "")+ except Exception as e:+ await log(f"there was an error signing into {url.host}")+ await log(e)+ return++ await log("Finished scrape of " + str(url))+ return cascade++ async def parse_thread(self, session: Session, url: URL, cascade: CascadeItem, title: str):+ try:+ soup = await session.get_BS4(url)++ domain = URL("https://" + url.host)++ title_block = soup.select_one("h1[class=p-title-value]")+ for elem in title_block.find_all("a"):+ elem.decompose()++ if title:+ pass+ else:+ title = title_block.text+ if self.include_id:+ titlep2 = url.name+ titlep2 = [s for s in titlep2 if "." in s][-1]+ title = title + " - " + titlep2+ title = await make_title_safe(title.replace(r"\n", "").strip())++ content_links = []++ post_number = str(url).split("post-")+ post_number = int(post_number[-1].strip("/")) if len(post_number) == 2 else None++ posts = soup.select("div[class='message-main uix_messageContent js-quickEditTarget']")+ for post in posts:+ post_num_str = post.select_one("li[class=u-concealed] a").get('href').split('/')[-1]+ post_num_int = int(post_num_str.split('post-')[-1])+ if post_number:+ if post_number > post_num_int:+ continue++ temp_title = title+"/"+post_num_str if self.separate_posts else title++ for elem in post.find_all('blockquote'):+ elem.decompose()+ post_content = post.select_one("div[class=bbWrapper]")++ # Content links+ links = post_content.select('a')+ for link in links:+ link = link.get('href')+ if link.endswith("/"):+ link = link[:-1]+ if link.startswith('//'):+ link = "https:" + link+ elif link.startswith('/'):+ link = domain / link[1:]+ content_links.append([URL(link), temp_title])++ links = post.select("div[class='bbImageWrapper js-lbImage']")+ for link in links:+ link = link.get('data-src')+ if link.endswith("/"):+ link = link[:-1]+ if link.startswith('/'):+ link = domain / link[1:]+ content_links.append([URL(link), temp_title])++ links = post.select("div[class='bbImageWrapper lazyload js-lbImage']")+ for link in links:+ link = link.get('data-src')+ if link.endswith("/"):+ link = link[:-1]+ if link.startswith('//'):+ link = "https:" + link+ elif link.startswith('/'):+ link = domain / link[1:]+ content_links.append([URL(link), temp_title])++ links = post.select("video source")+ for link in links:+ link = link.get('src')+ if link.endswith("/"):+ link = link[:-1]+ if link.startswith('//'):+ link = "https:" + link+ elif link.startswith('/'):+ link = domain / link[1:]+ content_links.append([URL(link), temp_title])++ links = post.select('iframe[class=saint-iframe]')+ for link in links:+ link = link.get('src')+ content_links.append([URL(link), temp_title])++ attachments_block = post.select_one("section[class=message-attachments]")+ links = attachments_block.select("a[class='file-preview js-lbImage']") if attachments_block else []+ for link in links:+ link = link.get('href')+ if link.endswith("/"):+ link = link[:-1]+ if link.startswith('/'):+ link = domain / link[1:]+ in_prog_title = temp_title + "/Attachments"+ await cascade.add_to_album(url.host, in_prog_title, URL(link), url)++ links = post_content.select("span[data-s9e-mediaembed-iframe]")+ for link in links:+ embed_data = link.get("data-s9e-mediaembed-iframe")+ embed_data = embed_data.replace("\/\/", "https://www.")+ embed_data = embed_data.replace("\\", "")++ embed_url = re.search(r"https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)", embed_data)+ if embed_url:+ embed_url = URL(embed_url.group(+ 0).replace("www.", ""))+ content_links.append([embed_url, temp_title])++ forum_direct_urls = [x for x in content_links if x[0].host in url.host]+ content_links = [x for x in content_links if x not in forum_direct_urls]+ for link_title_bundle in forum_direct_urls:+ link = link_title_bundle[0]+ temp_title = link_title_bundle[1]+ in_prog_title = temp_title + "/Attachments"+ if str(link).endswith("/"):+ link = URL(str(link)[:-1])+ if 'attachments' in link.parts:+ await cascade.add_to_album(url.host, in_prog_title, link, url)+ if 'content' in link.parts:+ await cascade.add_to_album(url.host, in_prog_title, link, url)+ elif 'data' in link.parts:+ await cascade.add_to_album(url.host, in_prog_title, link, url)++ tasks = []+ for link_title_bundle in content_links:+ link = link_title_bundle[0]+ temp_title = link_title_bundle[1]+ tasks.append(self.scraping_mapper.map_url(link, temp_title))+ await asyncio.gather(*tasks)++ next_page = soup.select_one('a[class="pageNav-jump pageNav-jump--next"]')+ if next_page is not None:+ next_page = next_page.get('href')+ if next_page is not None:+ if next_page.startswith('/'):+ next_page = domain / next_page[1:]+ next_page = URL(next_page)+ title = await self.parse_thread(session, next_page, cascade, title)+ return++ except Exception as e:+ logger.debug("Error encountered while handling %s", str(url), exc_info=True)+ await log("Error scraping " + str(url))+ logger.debug(e)diff --git a/cyberdrop_dl/crawlers/__init__.py b/cyberdrop_dl/crawlers/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/cyberdrop_dl/main.py b/cyberdrop_dl/main.pyindex c66c4a259..2b1bec36d 100644--- a/cyberdrop_dl/main.py+++ b/cyberdrop_dl/main.py@@ -1,4 +1,5 @@import argparse+import multiprocessingfrom argparse import Namespaceimport asyncioimport logging@@ -9,11 +10,12 @@ from colorama import Forefrom yarl import URLfrom . import __version__ as VERSION-from .utils.base_functions import clear, log, logger, purge_dir, regex_links-from .utils.data_classes import AuthData, SkipData-from .utils.downloaders import get_downloaders-from .utils.scraper import scrape-from .utils.sql_helper import SQLHelper+from cyberdrop_dl.base_functions.base_functions import clear, log, logger, purge_dir, regex_links+from cyberdrop_dl.base_functions.data_classes import AuthData, SkipData+from cyberdrop_dl.base_functions.sql_helper import SQLHelper+from cyberdrop_dl.client.client import Client+from cyberdrop_dl.client.downloaders import get_downloaders+from cyberdrop_dl.scraper.scraper import scrapedef parse_args():@@ -36,6 +38,8 @@ def parse_args():parser.add_argument("--thotsbay-username", type=str, help="username to login to thotsbay", default=None)parser.add_argument("--thotsbay-password", type=str, help="password to login to thotsbay", default=None)parser.add_argument("--skip", dest="skip_hosts", choices=SkipData.supported_hosts, help="This removes host links from downloads", action="append", default=[])+ parser.add_argument("--ratelimit", type=int, help="this will add a ratelimiter to requests made in the program during scraping, the number you provide is in requests/seconds", default=50)+ parser.add_argument("--throttle", type=int, help="This is a throttle between requests during the downloading phase, the number is in seconds", default=0.5)parser.add_argument("links", metavar="link", nargs="*", help="link to content to download (passing multiple links is supported)", default=[])args = parser.parse_args()return args@@ -53,17 +57,26 @@ async def download_all(args: argparse.Namespace):await log(f"{input_file} created. Populate it and retry.")exit(1)+ client = Client(args.ratelimit, args.throttle)SQL_helper = SQLHelper(args.ignore_history, args.db_file)await SQL_helper.sql_initialize()+ threads = args.threads if args.threads != 0 else multiprocessing.cpu_count()+links = args.linkslinks = list(map(URL, links))with open(input_file, "r", encoding="utf8") as f:links += await regex_links(f.read())+thotsbay_auth = AuthData(args.thotsbay_username, args.thotsbay_password)skip_data = SkipData(args.skip_hosts)- content_object = await scrape(links, args.include_id, thotsbay_auth, args.separate_posts, skip_data)+ excludes = {'videos': args.exclude_videos, 'images': args.exclude_images, 'audio': args.exclude_audio,+ 'other': args.exclude_other}+ content_object = await scrape(links, client, args.include_id, thotsbay_auth, args.separate_posts,+ skip_data, threads)++if await content_object.is_empty():logging.error('ValueError No links')await log("No links found, check the URL.txt\nIf the link works in your web browser, "@@ -71,11 +84,10 @@ async def download_all(args: argparse.Namespace):await log("This program does not currently support password protected albums.", Fore.RED)exit(0)await clear()+downloaders = await get_downloaders(content_object, folder=args.output_folder, attempts=args.attempts,- disable_attempt_limit=args.disable_attempt_limit,- threads=args.threads, exclude_videos=args.exclude_videos,- exclude_images=args.exclude_images, exclude_audio=args.exclude_audio,- exclude_other=args.exclude_other, SQL_helper=SQL_helper)+ disable_attempt_limit=args.disable_attempt_limit, max_workers=threads,+ excludes=excludes, SQL_helper=SQL_helper, client=client)for downloader in downloaders:await downloader.download_content()diff --git a/cyberdrop_dl/scraper/__init__.py b/cyberdrop_dl/scraper/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/cyberdrop_dl/scraper/scraper.py b/cyberdrop_dl/scraper/scraper.pynew file mode 100644index 000000000..405a9a25a--- /dev/null+++ b/cyberdrop_dl/scraper/scraper.py@@ -0,0 +1,25 @@+import asyncio++import aiohttp+from colorama import Fore++from .scraper_helper import ScrapeMapper+from ..base_functions.base_functions import log+from ..base_functions.data_classes import AuthData, SkipData+from ..client.client import Client+++async def scrape(urls, client: Client, include_id: bool, thotsbay_auth: AuthData, separate_posts: bool,+ skip_data: SkipData, threads: int):+ await log("Starting Scrape", Fore.WHITE)++ scraper = ScrapeMapper(client=client, include_id=include_id, thotsbay_auth=thotsbay_auth,+ separate_posts=separate_posts, skip_data=skip_data, threads=threads)+ tasks = []+ for link in urls:+ tasks.append(scraper.map_url(link))+ await asyncio.gather(*tasks)++ Cascade = scraper.Cascade+ await Cascade.dedupe()+ return Cascadediff --git a/cyberdrop_dl/utils/scraper_helper.py b/cyberdrop_dl/scraper/scraper_helper.pysimilarity index 58%rename from cyberdrop_dl/utils/scraper_helper.pyrename to cyberdrop_dl/scraper/scraper_helper.pyindex 781365153..117d5c7ff 100644--- a/cyberdrop_dl/utils/scraper_helper.py+++ b/cyberdrop_dl/scraper/scraper_helper.py@@ -3,31 +3,35 @@ import asyncioimport aiofilesfrom yarl import URL-from .crawlers.Anonfiles_Spider import AnonfilesCrawler-from .crawlers.Bunkr_Spider import BunkrCrawler-from .crawlers.Coomer_Spider import CoomerCrawler-from .crawlers.Cyberdrop_Spider import CyberdropCrawler-from .crawlers.Cyberfile_Spider import CyberfileCrawler-from .crawlers.Erome_Spider import EromeCrawler-from .crawlers.Gfycat_Spider import GfycatCrawler-from .crawlers.GoFile_Spider import GofileCrawler-from .crawlers.Kemono_Spider import KemonoCrawler-from .crawlers.Pixeldrain_Crawler import PixelDrainCrawler-from .crawlers.Redgifs_Spider import RedGifsCrawler-from .crawlers.Saint_Spider import SaintCrawler-from .crawlers.ShareX_Spider import ShareXCrawler-from .crawlers.Thotsbay_Spider import ThotsbayCrawler-from .base_functions import log-from .data_classes import CascadeItem, SkipData-from .rate_limiting import AsyncRateLimiter+from ..client.client import Client+from ..client.client import Session+from ..crawlers.Anonfiles_Spider import AnonfilesCrawler+from ..crawlers.Bunkr_Spider import BunkrCrawler+from ..crawlers.Coomer_Spider import CoomerCrawler+from ..crawlers.Cyberdrop_Spider import CyberdropCrawler+from ..crawlers.Cyberfile_Spider import CyberfileCrawler+from ..crawlers.Erome_Spider import EromeCrawler+from ..crawlers.Gfycat_Spider import GfycatCrawler+from ..crawlers.GoFile_Spider import GofileCrawler+from ..crawlers.Kemono_Spider import KemonoCrawler+from ..crawlers.Pixeldrain_Crawler import PixelDrainCrawler+from ..crawlers.Redgifs_Spider import RedGifsCrawler+from ..crawlers.Saint_Spider import SaintCrawler+from ..crawlers.ShareX_Spider import ShareXCrawler+from ..crawlers.Thotsbay_Spider import ThotsbayCrawler+from ..base_functions.base_functions import log+from ..base_functions.data_classes import CascadeItem, SkipData+from ..client.rate_limiting import AsyncRateLimiterclass ScrapeMapper():- def __init__(self, *, session, include_id=False, thotsbay_auth=None, separate_posts=False, skip_data: SkipData):+ def __init__(self, *, include_id=False, thotsbay_auth=None, separate_posts=False, skip_data: SkipData,+ client: Client, threads: int):self.include_id = include_idself.separate_posts = separate_postsself.thotsbay_auth = thotsbay_auth- self.session = session++ self.client = clientself.Cascade = CascadeItem({})self.skip_data = skip_data@@ -46,7 +50,9 @@ class ScrapeMapper():self.sharex_crawler = Noneself.thotsbay_crawler = None+ self.jpgchurch_limiter = AsyncRateLimiter(19)self.semaphore = asyncio.Semaphore(1)+ self.total_semaphore = asyncio.Semaphore(threads)self.mapping = {"anonfiles.com": self.Anonfiles, "bunkr": self.Bunkr, "coomer.party": self.coomer,"cyberdrop": self.Cyberdrop, "cyberfile.is": self.cyberfile,"erome.com": self.Erome, "gfycat.com": self.gfycat,@@ -54,137 +60,166 @@ class ScrapeMapper():"kemono.party": self.Kemono, "pixeldrain.com": self.Pixeldrain,"pixl.is": self.ShareX, "putme.ga": self.ShareX,"putmega.com": self.ShareX, "redgifs.com": self.redgifs,- "saint.to": self.Saint, "thotsbay.com": self.ThotsBay}+ "saint.to": self.Saint, "thotsbay": self.ThotsBay}async def Anonfiles(self, url: URL, title=None):+ anonfiles_session = Session(self.client)if not self.anonfiles_crawler:self.anonfiles_crawler = AnonfilesCrawler(include_id=self.include_id)- domain_obj = await self.anonfiles_crawler.fetch(self.session, url)+ domain_obj = await self.anonfiles_crawler.fetch(anonfiles_session, url)if title:await domain_obj.append_title(title)await self.Cascade.add_albums(domain_obj)+ await anonfiles_session.exit_handler()async def Bunkr(self, url: URL, title=None):+ bunkr_session = Session(self.client)if not self.bunkr_crawler:self.bunkr_crawler = BunkrCrawler(include_id=self.include_id)- domain_obj = await self.bunkr_crawler.fetch(self.session, url)+ domain_obj = await self.bunkr_crawler.fetch(bunkr_session, url)if title:await domain_obj.append_title(title)await self.Cascade.add_albums(domain_obj)+ await bunkr_session.exit_handler()async def Cyberdrop(self, url: URL, title=None):+ cyberdrop_session = Session(self.client)if not self.cyberdrop_crawler:self.cyberdrop_crawler = CyberdropCrawler(include_id=self.include_id)- domain_obj = await self.cyberdrop_crawler.fetch(self.session, url)+ domain_obj = await self.cyberdrop_crawler.fetch(cyberdrop_session, url)if title:await domain_obj.append_title(title)await self.Cascade.add_albums(domain_obj)+ await cyberdrop_session.exit_handler()async def coomer(self, url: URL, title=None):+ coomer_session = Session(self.client)if not self.coomer_crawler:self.coomer_crawler = CoomerCrawler(include_id=self.include_id)- domain_obj = await self.coomer_crawler.fetch(self.session, url)+ domain_obj = await self.coomer_crawler.fetch(coomer_session, url)if title:await domain_obj.append_title(title)await self.Cascade.add_albums(domain_obj)+ await coomer_session.exit_handler()async def cyberfile(self, url: URL, title=None):+ cyberfile_session = Session(self.client)if not self.cyberfile_crawler:self.cyberfile_crawler = CyberfileCrawler()async with self.semaphore:- domain_obj = await self.cyberfile_crawler.fetch(self.session, url)+ domain_obj = await self.cyberfile_crawler.fetch(cyberfile_session, url)if title:await domain_obj.append_title(title)await self.Cascade.add_albums(domain_obj)+ await cyberfile_session.exit_handler()async def Erome(self, url: URL, title=None):+ erome_session = Session(self.client)if not self.erome_crawler:self.erome_crawler = EromeCrawler(include_id=self.include_id)- domain_obj = await self.erome_crawler.fetch(self.session, url)+ domain_obj = await self.erome_crawler.fetch(erome_session, url)if title:await domain_obj.append_title(title)await self.Cascade.add_albums(domain_obj)+ await erome_session.exit_handler()async def GoFile(self, url: URL, title=None):+ gofile_session = Session(self.client)if not self.gofile_crawler:try:self.gofile_crawler = GofileCrawler()except:await log("Couldn't start the GoFile crawler")return- domain_obj = await self.gofile_crawler.fetch(self.session, url)+ domain_obj = await self.gofile_crawler.fetch(gofile_session, url)if title:await domain_obj.append_title(title)await self.Cascade.add_albums(domain_obj)+ await gofile_session.exit_handler()async def Kemono(self, url: URL, title=None):+ kemono_session = Session(self.client)if not self.kemono_crawler:self.kemono_crawler = KemonoCrawler(include_id=self.include_id)- domain_obj = await self.kemono_crawler.fetch(self.session, url)+ domain_obj = await self.kemono_crawler.fetch(kemono_session, url)if title:await domain_obj.append_title(title)await self.Cascade.add_albums(domain_obj)+ await kemono_session.exit_handler()async def gfycat(self, url: URL, title=None):+ gfycat_session = Session(self.client)if not self.gfycat_crawler:- self.gfycat_crawler = GfycatCrawler(scraping_mapper=self, session=self.session)- content_url = await self.gfycat_crawler.fetch(self.session, url)+ self.gfycat_crawler = GfycatCrawler()+ content_url = await self.gfycat_crawler.fetch(gfycat_session, url)if content_url:if title:await self.Cascade.add_to_album("gfycat.com", f"{title}/gifs", content_url, url)else:await self.Cascade.add_to_album("gfycat.com", "gifs", content_url, url)+ await gfycat_session.exit_handler()async def Pixeldrain(self, url: URL, title=None):+ pixeldrain_session = Session(self.client)if not self.pixeldrain_crawler:self.pixeldrain_crawler = PixelDrainCrawler()- domain_obj = await self.pixeldrain_crawler.fetch(self.session, url)+ domain_obj = await self.pixeldrain_crawler.fetch(pixeldrain_session, url)if title:await domain_obj.append_title(title)await self.Cascade.add_albums(domain_obj)+ await pixeldrain_session.exit_handler()async def redgifs(self, url: URL, title=None):+ redgifs_session = Session(self.client)if not self.redgifs_crawler:- self.redgifs_crawler = RedGifsCrawler(scraping_mapper=self, session=self.session)- content_url = await self.redgifs_crawler.fetch(self.session, url)+ self.redgifs_crawler = RedGifsCrawler()+ content_url = await self.redgifs_crawler.fetch(redgifs_session, url)if content_url:if title:await self.Cascade.add_to_album("redgifs.com", f"{title}/gifs", content_url, url)else:await self.Cascade.add_to_album("redgifs.com", "gifs", content_url, url)+ await redgifs_session.exit_handler()++ async def Saint(self, url: URL, title=None):+ saint_session = Session(self.client)+ if not self.saint_crawler:+ self.saint_crawler = SaintCrawler(include_id=self.include_id)+ domain_obj = await self.saint_crawler.fetch(saint_session, url)+ if title:+ await domain_obj.append_title(title)+ await self.Cascade.add_albums(domain_obj)+ await saint_session.exit_handler()async def ShareX(self, url: URL, title=None):+ sharex_session = Session(self.client)if not self.sharex_crawler:self.sharex_crawler = ShareXCrawler(include_id=self.include_id)- if "jpg.church" in url.host:- async with AsyncRateLimiter(19):- domain_obj = await self.sharex_crawler.fetch(self.session, url)+ if "jpg.church" in url.host and sharex_session.client.ratelimit > 19:+ async with self.jpgchurch_limiter:+ domain_obj = await self.sharex_crawler.fetch(sharex_session, url)else:- domain_obj = await self.sharex_crawler.fetch(self.session, url)+ domain_obj = await self.sharex_crawler.fetch(sharex_session, url)if title:await domain_obj.append_title(title)- await self.Cascade.add_albums(domain_obj)- async def Saint(self, url: URL, title=None):- if not self.saint_crawler:- self.saint_crawler = SaintCrawler(include_id=self.include_id)- domain_obj = await self.saint_crawler.fetch(self.session, url)- if title:- await domain_obj.append_title(title)await self.Cascade.add_albums(domain_obj)+ await sharex_session.exit_handler()async def ThotsBay(self, url: URL, title=None):+ thotsbay_session = Session(self.client)if not self.thotsbay_crawler:- self.thotsbay_crawler = ThotsbayCrawler(- include_id=self.include_id, auth=self.thotsbay_auth,- scraping_mapper=self, session=self.session, separate_posts=self.separate_posts)- await self.Cascade.extend(await self.thotsbay_crawler.fetch(self.session, url))+ self.thotsbay_crawler = ThotsbayCrawler(include_id=self.include_id, auth=self.thotsbay_auth,+ scraping_mapper=self, separate_posts=self.separate_posts)+ await self.Cascade.extend(await self.thotsbay_crawler.fetch(thotsbay_session, url))+ await thotsbay_session.exit_handler()async def map_url(self, url_to_map: URL, title=None):for key, value in self.mapping.items():if key in url_to_map.host:if key not in self.skip_data.sites:- await value(url=url_to_map, title=title)+ async with self.total_semaphore:+ await value(url=url_to_map, title=title)else:await log("Skipping scrape of " + str(url_to_map))returndiff --git a/cyberdrop_dl/utils/crawlers/Anonfiles_Spider.py b/cyberdrop_dl/utils/crawlers/Anonfiles_Spider.pydeleted file mode 100644index db20bcb02..000000000--- a/cyberdrop_dl/utils/crawlers/Anonfiles_Spider.py+++ /dev/null@@ -1,36 +0,0 @@-from bs4 import BeautifulSoup-from colorama import Fore-from yarl import URL--from ..base_functions import log, logger, ssl_context-from ..data_classes import DomainItem---class AnonfilesCrawler():- def __init__(self, *, include_id=False):- self.include_id = include_id-- async def fetch(self, session, url):- domain_obj = DomainItem(url.host, {})-- await log("Starting scrape of " + str(url), Fore.WHITE)-- try:- async with session.get(url, ssl=ssl_context) as response:- text = await response.text()- soup = BeautifulSoup(text, 'html.parser')-- title = "Anonfiles"-- link = soup.select_one("a[id=download-url]")- link = URL(link.get('href'))- await domain_obj.add_to_album(title, link, url)-- except Exception as e:- logger.debug("Error encountered while handling %s", str(url), exc_info=True)- await log("Error scraping " + str(url))- logger.debug(e)-- await log("Finished scrape of " + str(url), Fore.WHITE)-- return domain_objdiff --git a/cyberdrop_dl/utils/crawlers/Bunkr_Spider.py b/cyberdrop_dl/utils/crawlers/Bunkr_Spider.pydeleted file mode 100644index 9ee2eab14..000000000--- a/cyberdrop_dl/utils/crawlers/Bunkr_Spider.py+++ /dev/null@@ -1,77 +0,0 @@-import json--from bs4 import BeautifulSoup-from colorama import Fore-from yarl import URL--from ..base_functions import log, logger, make_title_safe, ssl_context, check_direct, FILE_FORMATS, user_agent-from ..data_classes import DomainItem---class BunkrCrawler():- def __init__(self, *, include_id=False):- self.include_id = include_id-- async def fetch(self, session, url: URL):- domain_obj = DomainItem(url.host, {})-- if await check_direct(url):- ext = '.' + str(url).split('.')[-1]- if ext in FILE_FORMATS['Videos']:- url = URL(str(url).replace('https://cdn', 'https://media-files'))- await domain_obj.add_to_album(link=url, referral=url, title="Bunkr Loose Files")- return domain_obj-- if "stream.bunkr." in url.host:- link = await self.stream(session, url)- await domain_obj.add_to_album(link=link, referral=url, title="Bunkr Loose Files")- await log("Finished scrape of " + str(url), Fore.WHITE)- return domain_obj-- await log("Starting scrape of " + str(url), Fore.WHITE)-- try:- async with session.get(url, ssl=ssl_context) as response:- text = await response.text()- soup = BeautifulSoup(text, 'html.parser')- build_id = json.loads(soup.select_one("script[id=__NEXT_DATA__]").get_text())-- json_fetch = URL("https://" + url.host + "/_next/data/" + build_id['buildId'] + url.path + '.json')- async with session.get(json_fetch, ssl=ssl_context) as response:- text = await response.text()- json_obj = json.loads(text)['pageProps']- title = await make_title_safe(json_obj['album']['name'])- for file in json_obj['files']:- ext = '.' + file['name'].split('.')[-1].lower()- if ext in FILE_FORMATS['Videos']:- cdn_loc = file['cdn']- media_loc = cdn_loc.replace('cdn', 'media-files')- link = URL(media_loc + '/' + file['name'])- else:- link = URL(file['cdn'] + '/' + file['name'])- await domain_obj.add_to_album(title, link, url)-- except Exception as e:- logger.debug("Error encountered while handling %s", str(url), exc_info=True)- await log("Error scraping " + str(url))- logger.debug(e)-- await log("Finished scrape of " + str(url), Fore.WHITE)-- return domain_obj-- async def stream(self, session, url):- try:- async with session.get(url, ssl=ssl_context, headers={'Referer': str(url), 'user-agent': user_agent}) as response:- text = await response.text()- soup = BeautifulSoup(text, 'html.parser')- json_obj = json.loads(soup.select_one("script[id=__NEXT_DATA__]").text)- if not json_obj['props']['pageProps']:- raise Exception("Couldn't get link from HTML")- link = URL(json_obj['props']['pageProps']['file']['mediafiles'] + '/' + json_obj['props']['pageProps']['file']['name'])- return link-- except Exception as e:- logger.debug("Error encountered while handling %s", str(url), exc_info=True)- await log("Error scraping " + str(url))- logger.debug(e)diff --git a/cyberdrop_dl/utils/crawlers/Coomer_Spider.py b/cyberdrop_dl/utils/crawlers/Coomer_Spider.pydeleted file mode 100644index 90ed74542..000000000--- a/cyberdrop_dl/utils/crawlers/Coomer_Spider.py+++ /dev/null@@ -1,87 +0,0 @@-from bs4 import BeautifulSoup-from colorama import Fore-from yarl import URL--from ..base_functions import log, logger, ssl_context, make_title_safe-from ..data_classes import DomainItem---class CoomerCrawler:- def __init__(self, *, include_id=False):- self.include_id = include_id-- async def fetch(self, session, url: URL):- await log("Starting scrape of " + str(url), Fore.WHITE)- domain_obj = DomainItem('coomer.party', {})- results = []-- if "thumbnail" in url.parts:- parts = [x for x in url.parts if x not in ("thumbnail", "/")]- link = URL("https://coomer.party/" + "/".join(parts))- await domain_obj.add_to_album("Loose Coomer.Party Files", link, link)- elif "data" in url.parts:- await domain_obj.add_to_album("Loose Coomer.Party Files", url, url)- else:- results.extend(await self.parse_profile(session, url))-- for result in results:- await domain_obj.add_to_album(result[0], result[1], result[2])-- await log("Finished scrape of " + str(url), Fore.WHITE)- return domain_obj-- async def parse_profile(self, session, url: URL):- try:- async with session.get(url, ssl=ssl_context) as response:- text = await response.text()- soup = BeautifulSoup(text, 'html.parser')- title = soup.select_one("span[itemprop=name]").get_text()- title = title + " (Coomer.party)"- results = []-- posts = soup.select("a[class=fancy-link]")- for post in posts:- path = post.get('href')- if path:- post_link = URL("https://coomer.party" + path)- results.extend(await self.parse_post(session, post_link, title))-- next_page = soup.select_one('a[title="Next page"]')- if next_page:- next_page = next_page.get('href')- if next_page:- results.extend(await self.parse_profile(session, URL("https://coomer.party" + next_page)))- return results-- except Exception as e:- logger.debug("Error encountered while handling %s", str(url), exc_info=True)- await log("Error scraping " + str(url))- logger.debug(e)- return []-- async def parse_post(self, session, url: URL, title: str):- try:- async with session.get(url, ssl=ssl_context) as response:- text = await response.text()- soup = BeautifulSoup(text, 'html.parser')- results = []-- title = title + '/' + await make_title_safe(soup.select_one("h1[class=post__title]").text.replace('\n', '').replace("..", ""))-- images = soup.select('a[class="fileThumb"]')- for image in images:- image_link = URL("https://coomer.party" + image.get('href'))- results.append([title, image_link, url])-- downloads = soup.select('a[class=post__attachment-link]')- for download in downloads:- download_link = URL("https://coomer.party" + download.get('href'))- results.append([title, download_link, url])-- return results-- except Exception as e:- logger.debug("Error encountered while handling %s", str(url), exc_info=True)- await log("Error scraping " + str(url))- logger.debug(e)- return []diff --git a/cyberdrop_dl/utils/crawlers/Cyberdrop_Spider.py b/cyberdrop_dl/utils/crawlers/Cyberdrop_Spider.pydeleted file mode 100644index 0b4100574..000000000--- a/cyberdrop_dl/utils/crawlers/Cyberdrop_Spider.py+++ /dev/null@@ -1,49 +0,0 @@-from bs4 import BeautifulSoup-from colorama import Fore-from yarl import URL--from ..base_functions import log, logger, make_title_safe, ssl_context, check_direct-from ..data_classes import DomainItem---class CyberdropCrawler():- def __init__(self, *, include_id=False):- self.include_id = include_id-- async def fetch(self, session, url):- domain_obj = DomainItem(url.host, {})-- if await check_direct(url):- link = URL(url)- await domain_obj.add_to_album(link=link, referral=url, title="Cyberdrop Loose Files")- return domain_obj-- await log("Starting scrape of " + str(url), Fore.WHITE)-- try:- async with session.get(url, ssl=ssl_context) as response:- text = await response.text()- soup = BeautifulSoup(text, 'html.parser')-- title = soup.select_one("h1[id=title]").get_text()- if title is None:- title = url.name- elif self.include_id:- titlep2 = url.name- titlep2 = [s for s in titlep2 if "." in s][-1]- title = title + " - " + titlep2- title = await make_title_safe(title.replace(r"\n", "").strip())-- links = soup.select('div[class="image-container column"] a')- for link in links:- link = URL(link.get('href'))- await domain_obj.add_to_album(title, link, url)-- except Exception as e:- logger.debug("Error encountered while handling %s", str(url), exc_info=True)- await log("Error scraping " + str(url))- logger.debug(e)-- await log("Finished scrape of " + str(url), Fore.WHITE)-- return domain_objdiff --git a/cyberdrop_dl/utils/crawlers/Cyberfile_Spider.py b/cyberdrop_dl/utils/crawlers/Cyberfile_Spider.pydeleted file mode 100644index b3dea61c9..000000000--- a/cyberdrop_dl/utils/crawlers/Cyberfile_Spider.py+++ /dev/null@@ -1,202 +0,0 @@-import json--from bs4 import BeautifulSoup-from colorama import Fore-from yarl import URL--from ..base_functions import log, ssl_context, user_agent, logger-from ..data_classes import DomainItem---class CyberfileCrawler:- def __init__(self):- self.load_files = URL('https://cyberfile.is/account/ajax/load_files')- self.file_details = URL('https://cyberfile.is/account/ajax/file_details')-- async def folder_nodeId(self, session, url: URL):- try:- async with session.get(url, ssl=ssl_context) as response:- text = await response.text()- soup = BeautifulSoup(text, 'html.parser')- script_func = soup.select_one('div[class="page-container horizontal-menu with-sidebar fit-logo-with-sidebar logged-out clear-adblock"] script').text- script_func = script_func.split('loadImages(')[-1]- script_func = script_func.split(';')[0]- nodeId = int(script_func.split(',')[1].replace("'", ""))- return nodeId-- except Exception as e:- await log("Error scraping " + str(url))- logger.debug(e)- return 0-- async def get_single_contentId(self, session, url: URL):- try:- async with session.get(url, ssl=ssl_context) as response:- text = await response.text()- soup = BeautifulSoup(text, 'html.parser')- script_funcs = soup.select('script')- for script in script_funcs:- script_text = script.text- if script_text:- if "showFileInformation" in script_text:- parta = script_text.split("showFileInformation(")- parta = [x for x in parta if x[0].isdigit()][0]- partb = parta.split(");")[0]- contentId = int(partb)- return contentId- return None-- except Exception as e:- await log("Error scraping " + str(url))- logger.debug(e)- return 0-- async def shared_nodeId_root_content(self, session, url: URL, page):- try:- # Initial page load to tell server, this is what we want.- async with session.get(str(url), headers={'referer': str(url), "user-agent": user_agent}, ssl=ssl_context) as response:- pass-- # get the content listings- data = {"pageType": "nonaccountshared", "nodeId": '', "pageStart": page, "perPage": 0, "filterOrderBy": ""}- nodes = []- contents = []- async with session.post(self.load_files, data=data, headers={"user-agent": user_agent}, ssl=ssl_context) as response:- content = json.loads(await response.content.read())- text = content['html']- title = content['page_title']- soup = BeautifulSoup(text.replace("\\", ""), 'html.parser')- total_pages = int(soup.select_one('input[id=rspTotalPages]').get('value'))- listings = soup.select("div[class=fileListing] div")- for listing in listings:- title = content['page_title']- try:- title = title + '/' + listing.select_one('span[class=filename]').text- nodes.append((title, int(listing.get('folderid'))))- except (TypeError, AttributeError):- pass- try:- contents.append((title, int(listing.get('fileid'))))- except TypeError:- pass- if page < total_pages:- nodes_temp, content_temp = await self.shared_nodeId_root_content(session, url, page+1)- nodes.extend(nodes_temp)- contents.extend(content_temp)- return nodes, contents-- except Exception as e:- await log("Error scraping " + str(url))- logger.debug(e)- return []-- async def shared_content(self, session, url: URL, nodeId, page, title=None):- try:- nodes = []- contents = []- data = {"pageType": "nonaccountshared", "nodeId": nodeId, "pageStart": page, "perPage": 0, "filterOrderBy": ""}- async with session.post(self.load_files, data=data, headers={"user-agent": user_agent}, ssl=ssl_context) as response:- content = json.loads(await response.content.read())- text = content['html']- title = title if title else content['page_title']- soup = BeautifulSoup(text.replace("\\", ""), 'html.parser')- total_pages = int(soup.select_one('input[id=rspTotalPages]').get('value'))- listings = soup.select("div[class=fileListing] div")- for listing in listings:- try:- nodes.append(int(listing.get('folderid')))- except TypeError:- pass- try:- contents.append((title, int(listing.get('fileid'))))- except TypeError:- pass- if page < total_pages:- contents.extend(await self.shared_content(session, url, nodeId, page+1, title))- for node in nodes:- contents.extend(await self.shared_content(session, url, node, 1, title))- return contents-- except Exception as e:- await log("Error scraping " + str(url))- logger.debug(e)- return []-- async def folder_content(self, session, url: URL, nodeId, page):- data = {"pageType": "folder", "nodeId": nodeId, "pageStart": page, "perPage": 0, "filterOrderBy": ""}- nodes = []- contents = []- try:- async with session.post(self.load_files, data=data, headers={"user-agent": user_agent}, ssl=ssl_context) as response:- content = json.loads(await response.content.read())- text = content['html']- title = content['page_title']- soup = BeautifulSoup(text.replace("\\", ""), 'html.parser')- total_pages = int(soup.select_one('input[id=rspTotalPages]').get('value'))- listings = soup.select("div[class=fileListing] div")- for listing in listings:- try:- nodes.append(int(listing.get('folderid')))- except TypeError:- pass- try:- contents.append((title, int(listing.get('fileid'))))- except TypeError:- pass- if page < total_pages:- contents.extend(await self.folder_content(session, url, nodeId, page+1))- for node in nodes:- contents.extend(await self.folder_content(session, url, node, 1))- return contents-- except Exception as e:- await log("Error scraping " + str(url))- logger.debug(e)- return []-- async def get_download_links(self, session, url, contentIds):- download_links = []- try:- for title, contentId in contentIds:- data = {"u": contentId}- async with session.post(self.file_details, data=data, headers={"user-agent": user_agent}, ssl=ssl_context) as response:- text = await response.text()- soup = BeautifulSoup(text.replace("\\", ""), 'html.parser')- menu = soup.select_one('ul[class="dropdown-menu dropdown-info account-dropdown-resize-menu"] li a')- button = soup.select_one('div[class="btn-group responsiveMobileMargin"] button')- if menu:- html_download_text = menu.get("onclick")- link = URL(html_download_text.replace("openUrl('", "").replace("'); return false;", ""))- download_links.append((title, link))- elif button:- html_download_text = button.get("onclick")- link = URL(html_download_text.replace("openUrl('", "").replace("'); return false;", ""))- download_links.append((title, link))- return download_links-- except Exception as e:- await log("Error scraping " + str(url))- logger.debug(e)- return []-- async def fetch(self, session, url: URL):- await log("Starting scrape of " + str(url), Fore.WHITE)- domain_obj = DomainItem("cyberfile.is", {})- download_links = []- if 'folder' in url.parts:- nodeId = await self.folder_nodeId(session, url)- contentIds = await self.folder_content(session, url, nodeId, 1)- download_links = await self.get_download_links(session, url, contentIds)- elif 'shared' in url.parts:- nodeIds, contentIds = await self.shared_nodeId_root_content(session, url, 1)- for title, nodeId in nodeIds:- contentIds.extend(await self.shared_content(session, url, nodeId, 1, title))- download_links = await self.get_download_links(session, url, contentIds)- else:- contentId = await self.get_single_contentId(session, url)- if contentId:- download_links = await self.get_download_links(session, url, [("Loose Cyberfile Files", contentId)])- for title, download_link in download_links:- await domain_obj.add_to_album(title, download_link, url)- await log("Finished scrape of " + str(url), Fore.WHITE)- return domain_objdiff --git a/cyberdrop_dl/utils/crawlers/Erome_Spider.py b/cyberdrop_dl/utils/crawlers/Erome_Spider.pydeleted file mode 100644index 05b6fa7de..000000000--- a/cyberdrop_dl/utils/crawlers/Erome_Spider.py+++ /dev/null@@ -1,46 +0,0 @@-from bs4 import BeautifulSoup-from colorama import Fore-from yarl import URL--from ..base_functions import log, logger, make_title_safe, ssl_context-from ..data_classes import DomainItem---class EromeCrawler():- def __init__(self, *, include_id=False):- self.include_id = include_id-- async def fetch(self, session, url):- domain_obj = DomainItem(url.host, {})-- await log("Starting scrape of " + str(url), Fore.WHITE)-- try:- async with session.get(url, ssl=ssl_context) as response:- text = await response.text()- soup = BeautifulSoup(text, 'html.parser')-- # Title- title = soup.select_one('div[class="col-sm-12 page-content"] h1').get_text()- if title is None:- title = url.name- elif self.include_id:- title = title + " - " + url.name- title = await make_title_safe(title)-- # Images- for link in soup.select('img[class="img-front lasyload"]'):- await domain_obj.add_to_album(title, URL(link['data-src']), url)-- # Videos- for link in soup.select('div[class=media-group] div[class=video-lg] video source'):- await domain_obj.add_to_album(title, URL(link['src']), url)-- except Exception as e:- logger.debug("Error encountered while handling %s", str(url), exc_info=True)- await log("Error scraping " + str(url))- logger.debug(e)-- await log("Finished scrape of " + str(url), Fore.WHITE)-- return domain_objdiff --git a/cyberdrop_dl/utils/crawlers/Gfycat_Spider.py b/cyberdrop_dl/utils/crawlers/Gfycat_Spider.pydeleted file mode 100644index 426f15c93..000000000--- a/cyberdrop_dl/utils/crawlers/Gfycat_Spider.py+++ /dev/null@@ -1,36 +0,0 @@-from bs4 import BeautifulSoup-from yarl import URL--from ..base_functions import log, logger, ssl_context---class GfycatCrawler():- def __init__(self, *, scraping_mapper, session):- self.scraping_mapper = scraping_mapper- self.session = session- self.lock = 0-- async def fetch(self, session, url):- try:- async with session.get(url, ssl=ssl_context) as response:- text = await response.text()- soup = BeautifulSoup(text, 'html.parser')-- video = soup.select_one("video[class='video media']")- video_srcs = video.select("source")-- # Find the biggest video source, usually the host is giant.gyfcat- video_link = None- for src in video_srcs:- link = URL(src.get("src"))- if str(link.host).find("giant") != -1:- video_link = link- if video_link is None:- video_link = URL(video_srcs[0].get("src"))-- return video_link-- except Exception as e:- logger.debug("Error encountered while handling %s", str(url), exc_info=True)- await log("Error scraping " + str(url))- logger.debug(e)diff --git a/cyberdrop_dl/utils/crawlers/Kemono_Spider.py b/cyberdrop_dl/utils/crawlers/Kemono_Spider.pydeleted file mode 100644index 1f6c3cee7..000000000--- a/cyberdrop_dl/utils/crawlers/Kemono_Spider.py+++ /dev/null@@ -1,87 +0,0 @@-from bs4 import BeautifulSoup-from colorama import Fore-from yarl import URL--from ..base_functions import log, logger, ssl_context, make_title_safe-from ..data_classes import DomainItem---class KemonoCrawler:- def __init__(self, *, include_id=False):- self.include_id = include_id-- async def fetch(self, session, url: URL):- await log("Starting scrape of " + str(url), Fore.WHITE)- domain_obj = DomainItem('kemono.party', {})- results = []-- if "thumbnail" in url.parts:- parts = [x for x in url.parts if x not in ("thumbnail", "/")]- link = URL("https://kemono.party/" + "/".join(parts))- await domain_obj.add_to_album("Loose Kemono.Party Files", link, link)- elif "data" in url.parts:- await domain_obj.add_to_album("Loose Kemono.Party Files", url, url)- else:- results.extend(await self.parse_profile(session, url))-- for result in results:- await domain_obj.add_to_album(result[0], result[1], result[2])-- await log("Finished scrape of " + str(url), Fore.WHITE)- return domain_obj-- async def parse_profile(self, session, url: URL):- try:- async with session.get(url, ssl=ssl_context) as response:- text = await response.text()- soup = BeautifulSoup(text, 'html.parser')- title = soup.select_one("span[itemprop=name]").get_text()- title = title + " (Kemono.party)"- results = []-- posts = soup.select("a[class=fancy-link]")- for post in posts:- path = post.get('href')- if path:- post_link = URL("https://kemono.party" + path)- results.extend(await self.parse_post(session, post_link, title))-- next_page = soup.select_one('a[title="Next page"]')- if next_page:- next_page = next_page.get('href')- if next_page:- results.extend(await self.parse_profile(session, URL("https://kemono.party" + next_page)))- return results-- except Exception as e:- logger.debug("Error encountered while handling %s", str(url), exc_info=True)- await log("Error scraping " + str(url))- logger.debug(e)- return []-- async def parse_post(self, session, url: URL, title: str):- try:- async with session.get(url, ssl=ssl_context) as response:- text = await response.text()- soup = BeautifulSoup(text, 'html.parser')- results = []-- title = title + '/' + await make_title_safe(soup.select_one("h1[class=post__title]").text.replace('\n', '').replace("..", ""))-- images = soup.select('a[class="fileThumb"]')- for image in images:- image_link = URL("https://kemono.party" + image.get('href'))- results.append([title, image_link, url])-- downloads = soup.select('a[class=post__attachment-link]')- for download in downloads:- download_link = URL("https://kemono.party" + download.get('href'))- results.append([title, download_link, url])-- return results-- except Exception as e:- logger.debug("Error encountered while handling %s", str(url), exc_info=True)- await log("Error scraping " + str(url))- logger.debug(e)- return []diff --git a/cyberdrop_dl/utils/crawlers/Redgifs_Spider.py b/cyberdrop_dl/utils/crawlers/Redgifs_Spider.pydeleted file mode 100644index 0df502bdf..000000000--- a/cyberdrop_dl/utils/crawlers/Redgifs_Spider.py+++ /dev/null@@ -1,37 +0,0 @@-from bs4 import BeautifulSoup-from yarl import URL--from ..base_functions import log, logger, ssl_context---class RedGifsCrawler():- def __init__(self, *, scraping_mapper, session):- self.scraping_mapper = scraping_mapper- self.session = session- self.lock = 0-- async def fetch(self, session, url):- try:- async with session.get(url, ssl=ssl_context) as response:- text = await response.text()- soup = BeautifulSoup(text, 'html.parser')-- video_metas = soup.select("meta[property='og:video']")-- # Find the video that doesn't contain "mobile"- video_src = None- for video_meta in video_metas:- link = video_meta.get("content")- if "mobile" not in link:- video_src = URL(link)-- # Just get the first one if we didn't find the non-mobile- if video_src is None and len(video_metas) != 0:- video_src = URL(video_metas[0].get("content"))-- return video_src-- except Exception as e:- logger.debug("Error encountered while handling %s", str(url), exc_info=True)- await log("Error scraping " + str(url))- logger.debug(e)diff --git a/cyberdrop_dl/utils/crawlers/Saint_Spider.py b/cyberdrop_dl/utils/crawlers/Saint_Spider.pydeleted file mode 100644index a584ed661..000000000--- a/cyberdrop_dl/utils/crawlers/Saint_Spider.py+++ /dev/null@@ -1,31 +0,0 @@-from bs4 import BeautifulSoup-from colorama import Fore-from yarl import URL--from ..base_functions import log, logger, ssl_context-from ..data_classes import DomainItem---class SaintCrawler():- def __init__(self, *, include_id=False):- self.include_id = include_id-- async def fetch(self, session, url):- domain_obj = DomainItem(url.host, {})- await log("Starting scrape of " + str(url), Fore.WHITE)-- try:- async with session.get(url, ssl=ssl_context) as response:- text = await response.text()- soup = BeautifulSoup(text, 'html.parser')- link = URL(soup.select_one('video[id=main-video] source').get('src'))- await domain_obj.add_to_album("Saint Loose Files", link, url)-- except Exception as e:- logger.debug("Error encountered while handling %s", str(url), exc_info=True)- await log("Error scraping " + str(url))- logger.debug(e)-- await log("Finished scrape of " + str(url), Fore.WHITE)-- return domain_objdiff --git a/cyberdrop_dl/utils/crawlers/ShareX_Spider.py b/cyberdrop_dl/utils/crawlers/ShareX_Spider.pydeleted file mode 100644index e8bb5dcc7..000000000--- a/cyberdrop_dl/utils/crawlers/ShareX_Spider.py+++ /dev/null@@ -1,168 +0,0 @@-import asyncio--from bs4 import BeautifulSoup-from colorama import Fore-from yarl import URL--from ..base_functions import log, logger, make_title_safe, ssl_context, check_direct-from ..data_classes import DomainItem---class ShareXCrawler():- def __init__(self, *, include_id=False):- self.include_id = include_id-- async def fetch(self, session, url):- domain_obj = DomainItem(url.host, {})-- await log("Starting scrape of " + str(url), Fore.WHITE)-- if await check_direct(url):- url = url.with_name(url.name.replace('.md.', '.').replace('.th.', '.'))- await domain_obj.add_to_album(link=url, referral=url, title="ShareX Loose Files")- return domain_obj-- if "album" in url.parts or "a" in url.parts:- results = await self.parse(url, session)- elif "albums" in url.parts:- results = await self.get_albums(url, session)- elif 'image' in url.parts or 'img' in url.parts or 'images' in url.parts:- results = await self.get_singular(url, session)- else:- results = await self.parse_profile(url, session)-- for result in results:- await domain_obj.add_to_album(result['title'], result['url'], result['referral'])-- await log("Finished scrape of " + str(url), Fore.WHITE)-- return domain_obj-- async def get_albums(self, url, session):- results = []- try:- async with session.get(url, ssl=ssl_context) as response:- text = await response.text()- soup = BeautifulSoup(text, 'html.parser')- albums = soup.select("a[class='image-container --media']")- for album in albums:- album_url = URL(album.get('href'))- results.extend(result for result in await self.parse(album_url, session))- except Exception as e:- logger.debug("Error encountered while handling %s", str(url), exc_info=True)- await log("Error scraping " + str(url))- logger.debug(e)- return results-- async def get_singular(self, url, session):- results = []- await asyncio.sleep(1)- try:- async with session.get(url, ssl=ssl_context) as response:- text = await response.text()- soup = BeautifulSoup(text, 'html.parser')- link = URL(soup.select_one("input[id=embed-code-2]").get('value'))- link = link.with_name(link.name.replace('.md.', '.').replace('.th.', '.'))- title = "ShareX Loose Files"- results.append({'url': link, 'title': title, 'referral': url, 'cookies': ''})- except Exception as e:- logger.debug("Error encountered while handling %s", str(url), exc_info=True)- await log("Error scraping " + str(url))- logger.debug(e)- return results-- async def get_sub_album_links(self, url, session, og_title):- results = []- try:- async with session.get(url, ssl=ssl_context) as response:- text = await response.text()- soup = BeautifulSoup(text, 'html.parser')- albums = soup.select("div[class=pad-content-listing] div")- for album in albums:- album_url = album.get('data-url-short')- if album_url is not None:- album_url = URL(album_url)- results.extend(result for result in await self.parse(album_url, session, og_title=og_title))- except Exception as e:- logger.debug("Error encountered while handling %s", str(url), exc_info=True)- await log("Error scraping " + str(url))- logger.debug(e)- return results-- async def parse_profile(self, url, session):- results = []- try:- async with session.get(url, ssl=ssl_context) as response:- text = await response.text()- soup = BeautifulSoup(text, 'html.parser')- title = soup.select_one("div[class=header] h1 strong").get_text()- if title is None:- title = url.name- elif self.include_id:- titlep2 = url.name- title = title + " - " + titlep2- title = await make_title_safe(title.replace(r"\n", "").strip())-- list_recent = URL(soup.select_one("a[id=list-most-recent-link]").get('href'))- results.extend(result for result in await self.get_list_links(list_recent, session, title))- except Exception as e:- logger.debug("Error encountered while handling %s", str(url), exc_info=True)- await log("Error scraping " + str(url))- logger.debug(e)- return results-- async def get_list_links(self, url, session, title):- results = []- try:- async with session.get(url, ssl=ssl_context) as response:- text = await response.text()- soup = BeautifulSoup(text, 'html.parser')- if url.host == 'jpg.church':- links = soup.select("a[href*=img] img")- else:- links = soup.select("a[href*=image] img")- for link in links:- link = URL(link.get('src'))- link = link.with_name(link.name.replace('.md.', '.').replace('.th.', '.'))- results.append({'url': link, 'title': title, 'referral': url, 'cookies': ''})- next_page = soup.select_one('li.pagination-next a')- if next_page is not None:- next_page = next_page.get('href')- if next_page is not None:- next_page = URL(next_page)- results.extend(result for result in await self.get_list_links(next_page, session, title))- except Exception as e:- logger.debug("Error encountered while handling %s", str(url), exc_info=True)- await log("Error scraping " + str(url))- logger.debug(e)- return results-- async def parse(self, url, session, og_title=None):- results = []- try:- async with session.get(url, ssl=ssl_context) as response:- text = await response.text()- soup = BeautifulSoup(text, 'html.parser')-- title = soup.select_one("a[data-text=album-name]").get_text()- if title is None:- title = url.name- elif self.include_id:- titlep2 = url.name- title = title + " - " + titlep2- title = await make_title_safe(title.replace(r"\n", "").strip())-- if og_title is not None:- title = og_title + "/" + title-- sub_albums = URL(soup.select_one("a[id=tab-sub-link]").get("href"))- results.extend(result for result in await self.get_sub_album_links(sub_albums, session, title))-- list_recent = URL(soup.select_one("a[id=list-most-recent-link]").get("href"))- results.extend(result for result in await self.get_list_links(list_recent, session, title))-- except Exception as e:- logger.debug("Error encountered while handling %s", str(url), exc_info=True)- await log("Error scraping " + str(url))- logger.debug(e)- return resultsdiff --git a/cyberdrop_dl/utils/crawlers/Thotsbay_Spider.py b/cyberdrop_dl/utils/crawlers/Thotsbay_Spider.pydeleted file mode 100644index b61c37945..000000000--- a/cyberdrop_dl/utils/crawlers/Thotsbay_Spider.py+++ /dev/null@@ -1,215 +0,0 @@-import asyncio-import re--from bs4 import BeautifulSoup-from colorama import Fore-from yarl import URL--from ..base_functions import log, logger, make_title_safe, ssl_context-from ..data_classes import AuthData, CascadeItem---class ThotsbayCrawler:- def __init__(self, *, include_id=False, auth: AuthData = None, scraping_mapper, session, separate_posts=False):- self.include_id = include_id- self.separate_posts = separate_posts- self.username, self.password = (auth.username, auth.password) if auth else (None, None)- self.scraping_mapper = scraping_mapper- self.session = session- self.lock = 0-- async def login(self, session, url: URL):- domain = URL("https://" + url.host) / "login"- async with session.get(domain, ssl=ssl_context) as response:- text = await response.text()- if "You are already logged in" in text:- return- soup = BeautifulSoup(text, 'html.parser')-- inputs = soup.select('form input')- data = {- elem['name']: elem['value']- for elem in inputs- if elem.get('name') and elem.get('value')- }- data.update({"login": self.username, "password": self.password})- return await session.post(domain/"login", data=data)-- async def fetch(self, session, url: URL):- await log("Starting scrape of " + str(url), Fore.WHITE)- Cascade = CascadeItem({})-- try:- if self.username and self.password:- while True:- if self.lock == 0:- self.lock = 1- await self.login(session, url)- self.lock = 0- break- await asyncio.sleep(2)- else:- await log("login wasn't provided, consider using --thotsbay-username and --thotsbay-password")- await log("Not being logged in might cause issues.")- await self.parse_thread(session, url, Cascade, None)- except Exception as e:- await log(f"there was an error signing into {url.host}")- await log(e)- return-- await log("Finished scrape of " + str(url), Fore.WHITE)- return Cascade-- async def parse_thread(self, session, url, Cascade, title):- try:- async with session.get(url, ssl=ssl_context) as response:- text = await response.text()- soup = BeautifulSoup(text, 'html.parser')-- domain = URL("https://" + url.host)-- title_block = soup.select_one("h1[class=p-title-value]")- for elem in title_block.find_all("a"):- elem.decompose()-- if title:- pass- else:- title = title_block.text- if self.include_id:- titlep2 = url.name- titlep2 = [s for s in titlep2 if "." in s][-1]- title = title + " - " + titlep2- title = await make_title_safe(title.replace(r"\n", "").strip())-- content_links = []-- post_number = str(url).split("post-")- post_number = int(post_number[-1].strip("/")) if len(post_number) == 2 else None-- posts = soup.select("div[class='message-main uix_messageContent js-quickEditTarget']")- for post in posts:- post_num_str = post.select_one("li[class=u-concealed] a").get('href').split('/')[-1]- post_num_int = int(post_num_str.split('post-')[-1])- if post_number:- if post_number > post_num_int:- continue-- temp_title = title+"/"+post_num_str if self.separate_posts else title-- for elem in post.find_all('blockquote'):- elem.decompose()- post_content = post.select_one("div[class=bbWrapper]")-- # Content links- links = post_content.select('a')- for link in links:- link = link.get('href')- if link.endswith("/"):- link = link[:-1]- if link.startswith('//'):- link = "https:" + link- elif link.startswith('/'):- link = domain / link[1:]- content_links.append([URL(link), temp_title])-- links = post.select("div[class='bbImageWrapper js-lbImage']")- for link in links:- link = link.get('data-src')- if link.endswith("/"):- link = link[:-1]- if link.startswith('/'):- link = domain / link[1:]- content_links.append([URL(link), temp_title])-- links = post.select("div[class='bbImageWrapper lazyload js-lbImage']")- for link in links:- link = link.get('data-src')- if link.endswith("/"):- link = link[:-1]- if link.startswith('//'):- link = "https:" + link- elif link.startswith('/'):- link = domain / link[1:]- content_links.append([URL(link), temp_title])-- links = post.select("video source")- for link in links:- link = link.get('src')- if link.endswith("/"):- link = link[:-1]- if link.startswith('//'):- link = "https:" + link- elif link.startswith('/'):- link = domain / link[1:]- content_links.append([URL(link), temp_title])-- links = post.select('iframe[class=saint-iframe]')- for link in links:- link = link.get('src')- content_links.append([URL(link), temp_title])-- attachments_block = post.select_one("section[class=message-attachments]")- links = attachments_block.select("a[class='file-preview js-lbImage']") if attachments_block else []- for link in links:- link = link.get('href')- if link.endswith("/"):- link = link[:-1]- if link.startswith('/'):- link = domain / link[1:]- in_prog_title = temp_title + "/Attachments"- await Cascade.add_to_album(url.host, in_prog_title, URL(link), url)-- # Gyfcat / Redgifs / Imgur- # NOTE IMGUR SUPPORT IS NOT WORKING AS OF NOW- links = post_content.select("span[data-s9e-mediaembed-iframe]")- for link in links:- embed_data = link.get("data-s9e-mediaembed-iframe")- # Replace gyfcat/redgifs/imgur embed url escape chars- embed_data = embed_data.replace("\/\/", "https://www.")- embed_data = embed_data.replace("\\", "")-- # extract gyfcat/redgifs/imgur url from embed data- embed_url = re.search(- "https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)", embed_data)- if embed_url:- embed_url = URL(embed_url.group(- 0).replace("www.", ""))- content_links.append([embed_url, temp_title])-- forum_direct_urls = [x for x in content_links if x[0].host in url.host]- content_links = [x for x in content_links if x not in forum_direct_urls]- for link_title_bundle in forum_direct_urls:- link = link_title_bundle[0]- temp_title = link_title_bundle[1]- in_prog_title = temp_title + "/Attachments"- if str(link).endswith("/"):- link = URL(str(link)[:-1])- if 'attachments' in link.parts:- await Cascade.add_to_album(url.host, in_prog_title, link, url)- if 'content' in link.parts:- await Cascade.add_to_album(url.host, in_prog_title, link, url)- elif 'data' in link.parts:- await Cascade.add_to_album(url.host, in_prog_title, link, url)-- tasks = []- for link_title_bundle in content_links:- link = link_title_bundle[0]- temp_title = link_title_bundle[1]- tasks.append(self.scraping_mapper.map_url(link, temp_title))- await asyncio.gather(*tasks)-- next_page = soup.select_one('a[class="pageNav-jump pageNav-jump--next"]')- if next_page is not None:- next_page = next_page.get('href')- if next_page is not None:- if next_page.startswith('/'):- next_page = domain / next_page[1:]- next_page = URL(next_page)- title = await self.parse_thread(session, next_page, Cascade, title)- return-- except Exception as e:- logger.debug("Error encountered while handling %s", str(url), exc_info=True)- await log("Error scraping " + str(url))- logger.debug(e)diff --git a/cyberdrop_dl/utils/scraper.py b/cyberdrop_dl/utils/scraper.pydeleted file mode 100644index 4db7b39bc..000000000--- a/cyberdrop_dl/utils/scraper.py+++ /dev/null@@ -1,27 +0,0 @@-import asyncio--import aiohttp-from colorama import Fore--from .base_functions import log, user_agent-from .data_classes import AuthData, SkipData-from .scraper_helper import ScrapeMapper---async def scrape(urls, include_id: bool, thotsbay_auth: AuthData, separate_posts: bool, skip_data: SkipData):- await log("Starting Scrape", Fore.WHITE)- headers = {"user-agent": user_agent}- jar = aiohttp.CookieJar(quote_cookie=False)-- async with aiohttp.ClientSession(headers=headers, raise_for_status=True, cookie_jar=jar) as session:- scraper = ScrapeMapper(session=session, include_id=include_id, thotsbay_auth=thotsbay_auth,- separate_posts=separate_posts, skip_data=skip_data)- tasks = []- for link in urls:- tasks.append(scraper.map_url(link))- await asyncio.gather(*tasks)-- Cascade = scraper.Cascade- Cascade.cookies = jar- await Cascade.dedupe()- return Cascade