Bulk asynchronous downloader for multiple file hosts
Python asynciobunkrcyberdropdownloaderdropboxfilestergofilegoogle-drivemediafiremegamega-nzonedrivepatreonpawchivepinterestpixeldraintransfer-ittwitchtwittervk
Working scraping/downloading. Rich instead of tqdm and colorama
Jules-WinnfieldX9b3049083492
diff --git a/LICENSE-THIRD-PARTY b/LICENSE-THIRD-PARTYdeleted file mode 100644index 32463f4de..000000000--- a/LICENSE-THIRD-PARTY+++ /dev/null@@ -1,2 +0,0 @@-Forked downloaders.py from https://github.com/alexdotis/Chibisafe-Sharex-Scraper/tree/feadd9c14e3307d07b174abbda0c6f40b608a0a4-Forked AsyncRateLimiter class from https://github.com/top-gg/python-sdk/blob/40d0156ef7e824c9ab4b6cb79142ed9539e29ce2/topgg/ratelimiter.py\ No newline at end of filediff --git a/Pipfile b/Pipfileindex 5db27ee9b..cfff5f051 100644--- a/Pipfile+++ b/Pipfile@@ -6,13 +6,10 @@ name = "pypi"[packages]aiofiles = "==22.1.0"aiohttp = "==3.8.3"-beautifulsoup4 = "==4.11.1"+beautifulsoup4 = "==4.11.2"certifi = "==2022.12.7"-colorama = "==0.4.6"-gofile_client = "==1.0.1"myjdapi = "==1.1.6"PyYAML = "==6.0"psutil = "==5.9.4"setuptools = "==65.6.3"-tqdm = "==4.64.1"yarl = "==1.8.2"\ No newline at end of filediff --git a/changelog.txt b/changelog.txtdeleted file mode 100644index f2fa74a92..000000000--- a/changelog.txt+++ /dev/null@@ -1,107 +0,0 @@-3.4.4-- Fixed config being recreated constantly due to typo.--3.4.5-- Added support to Coomer/Kemono for single post scraping.--3.4.6-- Fix bunkr cdn links.--3.4.7-- Fixed dict not copying correctly, wiping out login details for forum scraping.--3.4.9-- Fixed arg mapping in main func.--3.4.19-- A bunch including:-- Fixing some of kemono.party-- Fixing bunkr albums-- Simplifying requirements--3.4.21-- Better gofile exception handling-- Fix kemono next page--3.4.22-- Remove putmega/jpg.homes--3.4.23-- Fix bunkr images--3.4.25-- add pdf support--3.4.26-- code reorganization--3.4.28-- added support for files.bunkr.is--3.4.31-- added more line output during config creation/validation--3.5.4-- Fix skip sites--3.5.5-- Fix bug with pre-allocation--3.5.6-- Fix support for links with apostrophes--3.5.7-- Close client session after use instead of relying on deletion.-- Fix jpg.church infinite scroll/not getting all user albums.--3.5.8-- Follow links on Kemono/Coomer--3.5.9-- Change Kemono/Coomer to not separate posts unless flag is set.--3.5.11-- Add hgamecg support--3.5.17-- Reduce limiter for jpg.church to try and reduce timeouts (524 errors).--3.5.19-- Added error statement debug for jdownloader connection.--3.5.21-- Attempt fixes for login issue and JPG.Church--3.5.22-- One more jdownloader exception print.--3.6.9-- I haven't kept up with this. I implemented rescraping for some downloads that fail.-- Nice.--3.6.11-- If referrer is a forum, we don't rescrape.--3.6.12-- Removes file lock when file is already downloaded, avoids infinite loops in a fringe circumstance.--3.6.13-- Changes where the DB check is made, can incredibly boost the speed of skipping completed files in some circumstances.--3.6.21-- added pixeldrain api key support, kemono/coomer allow include_id, fixed cyberfile, fixed pixeldrain, fixed bunkr,--3.6.22-- dropping support for bayfiles--3.6.27-- Re-added bayfiles, rescraping no longer recreates the entire scraping objects (lead to unchecked requests with gofile)--3.6.38-- rescraping should now actually be working, minor bug fixes, updated requirements, should work with python 3.11 now.--3.6.48-- I forgot to do this log, lots of fixes.--3.6.49-- Removed kemono as they've implemented ddos-guard.\ No newline at end of filediff --git a/cyberdrop_dl/__init__.py b/cyberdrop_dl/__init__.pyindex 6653a1a46..76ad18b89 100644--- a/cyberdrop_dl/__init__.py+++ b/cyberdrop_dl/__init__.py@@ -1 +1 @@-__version__ = "3.6.51"+__version__ = "4.0.1"diff --git a/cyberdrop_dl/base_functions/base_functions.py b/cyberdrop_dl/base_functions/base_functions.pyindex bdad96d19..bdc0bb224 100644--- a/cyberdrop_dl/base_functions/base_functions.py+++ b/cyberdrop_dl/base_functions/base_functions.py@@ -1,25 +1,23 @@-from typing import Dict+from __future__ import annotations-import aiofilesimport loggingimport osimport refrom pathlib import Path+import aiofilesimport psutil as psutil-import yaml-from colorama import Fore, Style+import richfrom yarl import URL-from .config_schema import config_default, files_args, authentication_args, jdownloader_args, runtime_args--"""This file contains generic information and functions that are used around the program"""+from cyberdrop_dl.base_functions.data_classes import MediaItem+from cyberdrop_dl.base_functions.error_classes import NoExtensionFailureFILE_FORMATS = {'Images': {'.jpg', '.jpeg', '.png', '.gif',- '.webp', '.jpe', '.svg', '.jfif',- '.tif', '.tiff', '.jif',+ '.gifv', '.webp', '.jpe', '.svg',+ '.jfif', '.tif', '.tiff', '.jif',},'Videos': {'.mpeg', '.avchd', '.webm', '.mpv',@@ -27,40 +25,15 @@ FILE_FORMATS = {'.mp2', '.m4v', '.qt', '.mpe','.mp4', '.flv', '.mov', '.mpg','.ogg', '.mkv', '.mts', '.ts',+ '.f4v'},'Audio': {'.mp3', '.flac', '.wav', '.m4a',- },- 'Other': {- '.json', '.torrent', '.zip', '.rar',- '.7z', '.torrent', '.psd', '.pdf',}}-MAX_FILENAME_LENGTH = 100-logger = logging.getLogger(__name__)---class FailureException(Exception):- """Basic failure exception I can throw to force a retry."""-- def __init__(self, code, message="Something went wrong", rescrape=False):- self.code = code- self.message = message- self.rescrape = rescrape- super().__init__(self.message)- super().__init__(self.code)---async def sanitize(name: str) -> str:- return re.sub(r'[<>:"/\\|?*\']', "", name).strip()---async def log(text, style=Fore.WHITE, quiet=False) -> None:- logger.debug(text)- if not quiet:- print(style + str(text) + Style.RESET_ALL)+MAX_FILENAME_LENGTH = 100async def clear() -> None:@@ -68,27 +41,16 @@ async def clear() -> None:os.system('cls' if os.name == 'nt' else 'clear')-async def make_title_safe(title: str):- title = re.sub(r'[\\*?:"<>|./]', "-", title)- title = title[:60].rstrip()- return title---async def purge_dir(dirname, in_place=True):- deleted = []- dir_tree = list(os.walk(dirname, topdown=False))-- for tree_element in dir_tree:- sub_dir = tree_element[0]- dir_count = len(os.listdir(sub_dir))- if dir_count == 0: # Helps with readability and i've had issues with it deleting non-empty dirs- deleted.append(sub_dir)-- if in_place:- list(map(os.rmdir, deleted))+async def log(text, quiet=False) -> None:+ """Logs to the output log file and optionally prints to the terminal with given style"""+ logger.debug(text)+ if not quiet:+ rich.print(str(text))-async def regex_links(urls) -> list:+async def regex_links(urls: list) -> list:+ """Regex grab the links from the URLs.txt file"""+ """This allows code blocks or full paragraphs to be copy and pasted into the URLs.txt"""yarl_links = []for line in urls:if line.lstrip().startswith('#'):@@ -101,7 +63,8 @@ async def regex_links(urls) -> list:return yarl_links-async def check_free_space(required_space: int, download_directory: Path):+async def check_free_space(required_space: int, download_directory: Path) -> bool:+ """Checks if there is enough free space on the drive to continue operating"""free_space = psutil.disk_usage(str(download_directory.parent)).freefree_space = ((free_space / 1024) / 1024) / 1024if required_space > free_space:@@ -110,110 +73,78 @@ async def check_free_space(required_space: int, download_directory: Path):return True-async def cyberdrop_parse(url: URL) -> URL:- mapping_direct = [r'img-...cyberdrop...',- r'f.cyberdrop...', r'fs-...cyberdrop...']- url = str(url)- for mapping in mapping_direct:- url = re.sub(mapping, 'cyberdrop.to', url)- return URL(url)+async def allowed_filetype(media: MediaItem, block_images: bool, block_video: bool, block_audio: bool, block_other: bool):+ ext = media.ext+ if block_images:+ if ext in FILE_FORMATS["Images"]:+ return False+ if block_video:+ if ext in FILE_FORMATS["Videos"]:+ return False+ if block_audio:+ if ext in FILE_FORMATS["Audio"]:+ return False+ if block_other:+ if ext not in FILE_FORMATS["Images"] and ext not in FILE_FORMATS["Videos"] and ext not in FILE_FORMATS["Audio"]:+ return False+ return True+++async def purge_dir(dirname) -> None:+ """Purges empty directories"""+ deleted = []+ dir_tree = list(os.walk(dirname, topdown=False))++ for tree_element in dir_tree:+ sub_dir = tree_element[0]+ dir_count = len(os.listdir(sub_dir))+ if dir_count == 0: # Helps with readability and i've had issues with it deleting non-empty dirs+ deleted.append(sub_dir)+ list(map(os.rmdir, deleted))async def write_last_post_file(file: Path, url: str):+ """Writes the last post url from a thread to the specified file"""async with aiofiles.open(file, mode='a') as f:await f.write(url + '\n')return+async def get_db_path(url: URL):+ url_path = url.path+ if 'anonfiles' in url.host or 'bayfiles' in url.host:+ url_path = url.path+ url_path = url_path.split('/')+ url_path.pop(0)+ if len(url_path) > 1:+ url_path.pop(1)+ url_path = '/' + '/'.join(url_path)+ return url_path+++async def sanitize(name: str) -> str:+ """Simple sanitization to remove illegal characters"""+ return re.sub(r'[<>:"/\\|?*\']', "", name).strip()+++async def make_title_safe(title: str) -> str:+ """Simple sanitization to remove illegal characters from titles and trim the length to be less than 60 chars"""+ title = re.sub(r'[\\*?:"<>|./]', "-", title)+ title = title[:60].rstrip()+ return title++async def check_direct(url: URL):mapping_direct = [r'i.pixl.li', r'i..pixl.li', r'img-...cyberdrop...', r'f.cyberdrop...',- r'fs-...cyberdrop...', r'i.bunkr...', r'i..bunkr...', r'i...bunkr...', r'media-files.bunkr...',- r'media-files..bunkr...', r'cdn.bunkr...', r'cdn..bunkr...', r'cdn...bunkr...',- r'jpg.church/images/...', r'simp..jpg.church', r's..putmega.com', r's..putme.ga', r'images..imgbox.com' ]+ r'fs-...cyberdrop...', r'jpg.church/images/...', r'simp..jpg.church', r's..putmega.com',+ r's..putme.ga', r'images..imgbox.com']return any(re.search(domain, url.host) for domain in mapping_direct)-async def is_forum(url: URL):- mapping_forum = ['simpcity...', 'socialmediagirls....', 'xbunker...']- return any(re.search(domain, url.host) for domain in mapping_forum)--async def create_config(config: Path, passed_args=None, remake=None):- if config.is_file() and not remake:- logging.debug("Validating Config")- await validate_config(config)- return-- logging.debug("Creating Config File")- config_data = config_default- if passed_args:- for arg in authentication_args:- if arg in passed_args.keys():- config_data[0]["Configuration"]["Authentication"][arg] = passed_args[arg]- for arg in files_args:- if arg in passed_args.keys():- config_data[0]["Configuration"]["Files"][arg] = str(passed_args[arg])- for arg in jdownloader_args:- if arg in passed_args.keys():- config_data[0]["Configuration"]["JDownloader"][arg] = passed_args[arg]- for arg in runtime_args:- if arg in passed_args.keys():- config_data[0]["Configuration"]["Runtime"][arg] = passed_args[arg]-- with open(config, 'w') as yamlfile:- yaml.dump(config_data, yamlfile)- return---async def validate_config(config: Path):- with open(config, "r") as yamlfile:- data = yaml.load(yamlfile, Loader=yaml.FullLoader)- data = data[0]["Configuration"]- recreate = 0- try:- if not set(authentication_args).issubset(set(data['Authentication'].keys())):- recreate = 1- if not set(files_args).issubset(set(data['Files'].keys())):- recreate = 1- if not set(jdownloader_args).issubset(set(data['JDownloader'].keys())):- recreate = 1- if not set(runtime_args).issubset(set(data['Runtime'].keys())):- recreate = 1-- if recreate:- config.unlink()- logging.debug("Recreating Config")-- args = {}- args_list = [data['Authentication'], data['Files'], data['JDownloader'], data['Runtime']]- for dic in args_list:- args.update(dic)- await create_config(config, args, True)-- except KeyError:- config.unlink()- await log("Config was malformed, recreating.")- await create_config(config, None, True)---async def run_args(config: Path, cmd_arg: Dict):- with open(config, "r") as yamlfile:- data = yaml.load(yamlfile, Loader=yaml.FullLoader)- data = data[0]["Configuration"]- if data['Apply_Config']:- return data-- logging.debug("Gathering Args")- config_data = config_default[0]["Configuration"]- for arg in authentication_args:- if arg in cmd_arg.keys():- config_data["Authentication"][arg] = cmd_arg[arg]- for arg in files_args:- if arg in cmd_arg.keys():- config_data["Files"][arg] = cmd_arg[arg]- for arg in jdownloader_args:- if arg in cmd_arg.keys():- config_data["JDownloader"][arg] = cmd_arg[arg]- for arg in runtime_args:- if arg in cmd_arg.keys():- config_data["Runtime"][arg] = cmd_arg[arg]- return config_data+async def get_filename_and_ext(filename):+ filename_parts = filename.rsplit('.', 1)+ if len(filename_parts) == 1:+ raise NoExtensionFailure()+ ext = "." + filename_parts[-1].lower()+ filename = filename_parts[0] + ext+ return filename, extdiff --git a/cyberdrop_dl/base_functions/config_manager.py b/cyberdrop_dl/base_functions/config_manager.pynew file mode 100644index 000000000..b798a971c--- /dev/null+++ b/cyberdrop_dl/base_functions/config_manager.py@@ -0,0 +1,129 @@+from __future__ import annotations+import copy+from pathlib import Path++import yaml++from cyberdrop_dl.base_functions.base_functions import log+from cyberdrop_dl.base_functions.config_schema import config_default, authentication_args, files_args, \+ jdownloader_args, runtime_args, forum_args, ignore_args, ratelimiting_args+++def create_config(config: Path, passed_args=None, remake=None):+ """Creates the default config file, or remakes it with passed arguments"""+ if config.is_file() and not remake:+ validate_config(config)+ return++ config_data = config_default+ if passed_args:+ for arg in authentication_args:+ if arg in passed_args.keys():+ config_data[0]["Configuration"]["Authentication"][arg] = passed_args[arg]+ for arg in files_args:+ if arg in passed_args.keys():+ config_data[0]["Configuration"]["Files"][arg] = str(passed_args[arg])+ for arg in jdownloader_args:+ if arg in passed_args.keys():+ config_data[0]["Configuration"]["JDownloader"][arg] = passed_args[arg]+ for arg in runtime_args:+ if arg in passed_args.keys():+ config_data[0]["Configuration"]["Runtime"][arg] = passed_args[arg]++ with open(config, 'w') as yamlfile:+ yaml.dump(config_data, yamlfile)+ return+++def validate_config(config: Path):+ """Validates the existing config file"""+ with open(config, "r") as yamlfile:+ data = yaml.load(yamlfile, Loader=yaml.FullLoader)+ try:+ data = data[0]["Configuration"]+ recreate = 0++ if not set(authentication_args).issubset(set(data['Authentication'].keys())):+ recreate = 1+ if not set(files_args).issubset(set(data['Files'].keys())):+ recreate = 1+ if not set(forum_args).issubset(set(data['Forum_Options'].keys())):+ recreate = 1+ if not set(ignore_args).issubset(set(data['Ignore'].keys())):+ recreate = 1+ if not set(jdownloader_args).issubset(set(data['JDownloader'].keys())):+ recreate = 1+ if not set(ratelimiting_args).issubset(set(data['Ratelimiting'].keys())):+ recreate = 1+ if not set(runtime_args).issubset(set(data['Runtime'].keys())):+ recreate = 1++ if recreate:+ config.unlink()++ args = {}+ args_list = [data['Authentication'], data['Files'], data['Forum_Options'], data['Ignore'],+ data['JDownloader'], data['Ratelimiting'], data['Runtime']]+ for dic in args_list:+ args.update(dic)+ create_config(config, args, True)++ except (KeyError, TypeError):+ config.unlink()+ create_config(config, None, True)+++def run_args(config: Path, cmd_arg: dict):+ """Returns the proper runtime arguments based on the config and command line arguments"""+ create_config(config, cmd_arg)++ with open(config, "r") as yamlfile:+ data = yaml.load(yamlfile, Loader=yaml.FullLoader)+ data = data[0]["Configuration"]+ if data['Apply_Config']:+ for file, path in data['Files'].items():+ data['Files'][file] = Path(path)+ return data++ config_data = config_default[0]["Configuration"]+ for arg in authentication_args:+ if arg in cmd_arg.keys():+ config_data["Authentication"][arg] = cmd_arg[arg]+ for arg in files_args:+ if arg in cmd_arg.keys():+ config_data["Files"][arg] = cmd_arg[arg]+ for arg in forum_args:+ if arg in cmd_arg.keys():+ config_data["Forum_Options"][arg] = cmd_arg[arg]+ for arg in ignore_args:+ if arg in cmd_arg.keys():+ config_data["Ignore"][arg] = cmd_arg[arg]+ for arg in jdownloader_args:+ if arg in cmd_arg.keys():+ config_data["JDownloader"][arg] = cmd_arg[arg]+ for arg in ratelimiting_args:+ if arg in cmd_arg.keys():+ config_data["Ratelimiting"][arg] = cmd_arg[arg]+ for arg in runtime_args:+ if arg in cmd_arg.keys():+ config_data["Runtime"][arg] = cmd_arg[arg]+ return config_data+++async def document_args(args: dict):+ """We document the runtime arguments for debugging and troubleshooting, redacting sensitive information"""+ print_args = copy.deepcopy(args)+ print_args['Authentication']['xbunker_password'] = '!REDACTED!' if args['Authentication']['xbunker_password'] is not None else None+ print_args['Authentication']['socialmediagirls_password'] = '!REDACTED!' if args['Authentication']['socialmediagirls_password'] is not None else None+ print_args['Authentication']['simpcity_password'] = '!REDACTED!' if args['Authentication']['simpcity_password'] is not None else None+ print_args['Authentication']['pixeldrain_api_key'] = '!REDACTED!' if args['Authentication']['pixeldrain_api_key'] is not None else None+ print_args['JDownloader']['jdownloader_password'] = '!REDACTED!' if args['JDownloader']['jdownloader_password'] is not None else None++ await log(f"Starting Cyberdrop-DL")+ await log(f"Using authentication arguments: {print_args['Authentication']}", quiet=True)+ await log(f"Using file arguments: {print_args['Files']}", quiet=True)+ await log(f"Using forum option arguments: {print_args['Forum_Options']}", quiet=True)+ await log(f"Using ignore arguments: {print_args['Ignore']}", quiet=True)+ await log(f"Using jdownloader arguments: {print_args['JDownloader']}", quiet=True)+ await log(f"Using ratelimiting arguments: {print_args['Ratelimiting']}", quiet=True)+ await log(f"Using runtime arguments: {print_args['Runtime']}", quiet=True)diff --git a/cyberdrop_dl/base_functions/config_schema.py b/cyberdrop_dl/base_functions/config_schema.pyindex b33793dc3..7d55474cb 100644--- a/cyberdrop_dl/base_functions/config_schema.py+++ b/cyberdrop_dl/base_functions/config_schema.py@@ -3,10 +3,12 @@ config_default = ["Configuration": {"Apply_Config": False,"Files": {+ "db_file": "download_history.sqlite","input_file": "URLs.txt",+ "log_file": "downloader.log","output_folder": "Downloads","output_last_forum_post_file": "URLs_last_post.txt",- "db_file": "download_history.sqlite",+ "unsupported_urls_file": "Unsupported_URLs.csv",},"Authentication": {"pixeldrain_api_key": "",@@ -18,41 +20,58 @@ config_default = ["xbunker_password": "",},"JDownloader": {- "jdownloader_enable": False,+ "apply_jdownloader": False,"jdownloader_username": "","jdownloader_password": "","jdownloader_device": "",},- "Runtime": {- "threads": 0,- "attempts": 10,- "required_free_space": 5,- "disable_attempt_limit": False,- "connection_timeout": 15,- "ratelimit": 50,- "throttle": 0.5,- "include_id": False,+ "Forum_Options": {+ "output_last_forum_post": False,+ "separate_posts": False,+ },+ "Ignore": {"exclude_videos": False,"exclude_images": False,"exclude_audio": False,"exclude_other": False,+ "ignore_cache": False,"ignore_history": False,- "output_last_forum_post": False,- "separate_posts": False,+ "skip_hosts": [],+ },+ "Ratelimiting": {+ "connection_timeout": 15,+ "ratelimit": 50,+ "throttle": 0.5,+ },+ "Runtime": {+ "simultaneous_downloads": 0,+ "allow_insecure_connections": False,+ "attempts": 10,+ "required_free_space": 5,+ "disable_attempt_limit": False,+ "include_id": False,"mark_downloaded": False,"proxy": "",- "skip_hosts": [],}}}]-files_args = ["input_file", "output_folder", "output_last_forum_post_file", "db_file"]authentication_args = ["pixeldrain_api_key","simpcity_username", "simpcity_password","socialmediagirls_username", "socialmediagirls_password","xbunker_username", "xbunker_password"]-jdownloader_args = ["jdownloader_enable", "jdownloader_username", "jdownloader_password", "jdownloader_device"]-runtime_args = ["threads", "attempts", "disable_attempt_limit", "connection_timeout", "ratelimit", "throttle",- "include_id", "exclude_videos", "exclude_images", "exclude_audio", "exclude_other", "ignore_history",- "output_last_forum_post", "mark_downloaded", "separate_posts", "skip_hosts", "proxy", "required_free_space"]++files_args = ["db_file", "input_file", "log_file", "output_folder", "output_last_forum_post_file", "unsupported_urls_file"]++forum_args = ["output_last_forum_post", "separate_posts"]++ignore_args = ["exclude_videos", "exclude_images", "exclude_audio", "exclude_other", "ignore_cache", "ignore_history",+ "skip_hosts"]++jdownloader_args = ["apply_jdownloader", "jdownloader_username", "jdownloader_password", "jdownloader_device"]++ratelimiting_args = ["connection_timeout", "ratelimit", "throttle"]++runtime_args = ["simultaneous_downloads", "allow_insecure_connections", "attempts", "disable_attempt_limit",+ "include_id", "mark_downloaded", "proxy", "required_free_space"]diff --git a/cyberdrop_dl/base_functions/data_classes.py b/cyberdrop_dl/base_functions/data_classes.pyindex 2fb0a16b8..b96deba07 100644--- a/cyberdrop_dl/base_functions/data_classes.py+++ b/cyberdrop_dl/base_functions/data_classes.py@@ -1,72 +1,67 @@import asynciofrom dataclasses import dataclass+from pathlib import Pathfrom typing import ClassVar, Dict, List, Optional, Tuplefrom yarl import URL@dataclass-class FileLock:- locked_files = []-- async def check_lock(self, filename):- await asyncio.sleep(.1)- return filename.lower() in self.locked_files+class MediaItem:+ url: URL+ referrer: URL+ complete: bool+ filename: str+ ext: str- async def add_lock(self, filename):- self.locked_files.append(filename.lower())+ async def is_complete(self):+ return self.complete- async def remove_lock(self, filename):- self.locked_files.remove(filename.lower())+ async def mark_completed(self):+ self.complete = True@dataclassclass AlbumItem:"""Class for keeping track of download links for each album"""title: str- link_pairs: List[Tuple]- password: Optional[str] = None+ media: List[MediaItem]- async def add_link_pair(self, link, referral):- self.link_pairs.append((link, referral))+ async def add_media(self, media_item: MediaItem):+ self.media.append(media_item)async def set_new_title(self, new_title: str):self.title = new_title- async def get_referrer(self, link: URL):- for pair in self.link_pairs:- if link == pair[0]:- return pair[1]+ async def append_title(self, title):+ new_title = title + '/' + self.title+ self.title = new_title- async def replace_link_pairs(self, link_pairs_in):- map = {}- for link_pair in link_pairs_in:- for pair in self.link_pairs:- if link_pair[0].parts[-1] == pair[0].parts[-1]:- self.link_pairs.remove(pair)- self.link_pairs.append(link_pair)- map[pair[0]] = link_pair[0]- return map+ async def is_empty(self):+ if not self.media:+ return True+ return False@dataclassclass DomainItem:+ """Class for keeping track of albums for each scraper type"""domain: stralbums: Dict[str, AlbumItem]- async def add_to_album(self, title: str, link: URL, referral: URL):- if link:- if title in self.albums.keys():- await self.albums[title].add_link_pair(link, referral)- else:- self.albums[title] = AlbumItem(title=title, link_pairs=[(link, referral)])+ async def add_to_album(self, title: str, media: MediaItem):+ if title in self.albums.keys():+ await self.albums[title].add_media(media)+ else:+ self.albums[title] = AlbumItem(title=title, media=[media])async def add_album(self, title: str, album: AlbumItem):if title in self.albums.keys():stored_album = self.albums[title]- for link_pair in album.link_pairs:- link, referral = link_pair- await stored_album.add_link_pair(link, referral)+ for media_item in album.media:+ if media_item in stored_album.media:+ continue+ await stored_album.add_media(media_item)else:self.albums[title] = album@@ -92,11 +87,11 @@ class CascadeItem:for title, album in albums.items():await self.add_album(domain, title, album)- async def add_to_album(self, domain: str, title: str, link: URL, referral: URL):+ async def add_to_album(self, domain: str, title: str, media_item: MediaItem):if domain in self.domains.keys():- await self.domains[domain].add_to_album(title, link, referral)+ await self.domains[domain].add_to_album(title, media_item)else:- self.domains[domain] = DomainItem(domain, {title: AlbumItem(title, [(link, referral)])})+ self.domains[domain] = DomainItem(domain, {title: AlbumItem(title, [media_item])})async def add_album(self, domain: str, title: str, album: AlbumItem):if domain in self.domains.keys():@@ -107,11 +102,11 @@ class CascadeItem:async def is_empty(self):for _, domain in self.domains.items():for _, album in domain.albums.items():- if album.link_pairs:+ if album.media:return Falsereturn True- async def append_title(self, title):+ async def append_title(self, title: str):if not title:returnfor _, domain in self.domains.items():@@ -134,24 +129,70 @@ class CascadeItem:for _, album in domain.albums.items():check = []allowed = []- for pair in album.link_pairs:- url, _ = pair- if url in check:+ for media_item in album.media:+ if media_item.url in check:continue- check.append(url)- allowed.append(pair)- album.link_pairs = allowed+ check.append(media_item.url)+ allowed.append(media_item)+ album.media = allowed@dataclass-class AuthData:- """Class for keeping username and password"""- username: str- password: str+class ForumItem:+ threads: Dict[str, CascadeItem]++ async def add_album_to_thread(self, title: str, domain: str, album: AlbumItem):+ if title not in self.threads.keys():+ self.threads[title] = CascadeItem({domain: DomainItem(domain, {album.title: album})})+ else:+ await self.threads[title].add_album(domain, album.title, album)++ async def add_thread(self, title: str, cascade: CascadeItem):+ if title not in self.threads.keys():+ self.threads[title] = cascade+ else:+ await self.threads[title].extend(cascade)++ async def is_empty(self):+ for _, Cascade in self.threads.items():+ for _, domain in Cascade.domains.items():+ for _, album in domain.albums.items():+ if album.media:+ return False+ return True++ async def dedupe(self):+ for _, Cascade in self.threads.items():+ for _, domain in Cascade.domains.items():+ for _, album in domain.albums.items():+ check = []+ allowed = []+ for media_item in album.media:+ if media_item.url in check:+ continue+ check.append(media_item.url)+ allowed.append(media_item)+ album.media = allowed++@dataclass+class FileLock:+ """Rudimentary file lock system"""+ locked_files = []++ async def check_lock(self, filename):+ await asyncio.sleep(.1)+ return filename.lower() in self.locked_files++ async def add_lock(self, filename):+ self.locked_files.append(filename.lower())++ async def remove_lock(self, filename):+ self.locked_files.remove(filename.lower())@dataclassclass SkipData:+ """The allows optoins for domains to skip when scraping"""supported_hosts: ClassVar[Tuple[str]] = ("anonfiles", "bunkr", "coomer.party", "cyberdrop", "cyberfile", "erome", "fapello", "gfycat","gofile", "hgamecg", "imgbox", "img.kiwi", "jpg.church", "pixeldrain", "pixl.li", "postimg.cc",diff --git a/cyberdrop_dl/base_functions/error_classes.py b/cyberdrop_dl/base_functions/error_classes.pynew file mode 100644index 000000000..fb997255d--- /dev/null+++ b/cyberdrop_dl/base_functions/error_classes.py@@ -0,0 +1,26 @@+class JDownloaderFailure(Exception):+ """Basic failure template for JDownloader"""+ def __init__(self, message="Something went wrong"):+ self.message = message+ super().__init__(self.message)+++class NoExtensionFailure(Exception):+ """This error will be thrown when no extension is given for a file"""+ def __init__(self, *, message="Extension missing for file"):+ self.message = message+ super().__init__(self.message)+++class FailedLoginFailure(Exception):+ def __init__(self, *, message="Failed login."):+ self.message = message+ super().__init__(self.message)+++class DownloadFailure(Exception):+ def __init__(self, code, message="Something went wrong"):+ self.code = code+ self.message = message+ super().__init__(self.message)+ super().__init__(self.code)diff --git a/cyberdrop_dl/base_functions/sql_helper.py b/cyberdrop_dl/base_functions/sql_helper.pyindex 5413c1ffe..dbb7f6fb7 100644--- a/cyberdrop_dl/base_functions/sql_helper.py+++ b/cyberdrop_dl/base_functions/sql_helper.py@@ -1,12 +1,17 @@import atexitimport loggingimport sqlite3-import os+from pathlib import Path++from cyberdrop_dl.base_functions.base_functions import get_db_path+from cyberdrop_dl.base_functions.data_classes import AlbumItem, CascadeItem, MediaItemclass SQLHelper:- def __init__(self, ignore_history, download_history):+ """This class is responsible for handling SQL operations"""+ def __init__(self, ignore_history, ignore_cache, download_history):self.ignore_history = ignore_history+ self.ignore_cache = ignore_cacheself.download_history = download_historyself.conn = Noneself.curs = None@@ -14,24 +19,30 @@ class SQLHelper:atexit.register(self.exit_handler)async def sql_initialize(self):+ """Initializes the SQL connection, and makes sure necessary tables exist"""self.conn = sqlite3.connect(self.download_history)self.curs = self.conn.cursor()- await self.create_tables()await self.pre_allocate()-- await self.check_columns()-- async def create_tables(self):- create_table_query = """CREATE TABLE IF NOT EXISTS downloads (- path TEXT,- downloaded_filename TEXT,- completed INTEGER NOT NULL,- PRIMARY KEY (path)- );"""+ await self.create_media_history()+ await self.create_coomer_history()++ async def create_media_history(self):+ """We create the download history tables here"""+ create_table_query = """CREATE TABLE IF NOT EXISTS media (+ domain TEXT,+ url_path TEXT,+ album_path TEXT,+ referrer TEXT,+ download_path TEXT,+ download_filename TEXT,+ original_filename TEXT,+ completed INTEGER NOT NULL,+ PRIMARY KEY (url_path, original_filename)+ );"""create_temp_download_name_query = """CREATE TABLE IF NOT EXISTS downloads_temp (- downloaded_filename TEXT- );"""+ downloaded_filename TEXT+ );"""temp_truncate_query = """DELETE FROM downloads_temp;"""self.curs.execute(create_table_query)@@ -41,7 +52,17 @@ class SQLHelper:self.curs.execute(temp_truncate_query)self.conn.commit()+ async def create_coomer_history(self):+ create_table_query = """CREATE TABLE IF NOT EXISTS coomer (+ url_path TEXT,+ post_data BLOB,+ PRIMARY KEY (url_path)+ );"""+ self.curs.execute(create_table_query)+ self.conn.commit()+async def pre_allocate(self):+ """We pre-allocate 50MB of space to the SQL file just in case the user runs out of disk space"""pre_alloc = "CREATE TABLE IF NOT EXISTS t(x);"pre_alloc2 = "INSERT INTO t VALUES(zeroblob(50*1024*1024));" # 50 mbdrop_pre = "DROP TABLE t;"@@ -57,73 +78,94 @@ class SQLHelper:self.curs.execute(drop_pre)self.conn.commit()- async def check_columns(self):- self.curs.execute("""SELECT COUNT(*) AS CNTREC FROM pragma_table_info('downloads') WHERE- name='path'""")- sql_check = self.curs.fetchone()[0]- if sql_check == (0):- self.curs.execute("""DROP TABLE downloads""")- self.conn.commit()- create_table_query = """CREATE TABLE IF NOT EXISTS downloads (- path TEXT,- downloaded_filename TEXT,- completed INTEGER NOT NULL,- PRIMARY KEY (path)- );"""- self.curs.execute(create_table_query)- self.conn.commit()-- self.curs.execute("""PRAGMA table_info('downloads')""")- sql_check = self.curs.fetchall()- sql_check = list(sum(sql_check, ()))- columns = {'path': "TEXT", 'downloaded_filename': "TEXT", 'completed': "INTEGER NOT NULL", 'referrer': "TEXT"}- for column in columns.keys():- if column in sql_check:- continue- else:- query = "ALTER TABLE downloads ADD COLUMN {} {}".format(column, columns[column])- self.curs.execute(query)- self.conn.commit()--- async def sql_check_existing(self, path):- if self.ignore_history:- return False- self.curs.execute("""SELECT completed FROM downloads WHERE path = ?""", (path, ))- sql_file_check = self.curs.fetchone()- return sql_file_check and sql_file_check[0] == 1+ async def get_temp_names(self):+ self.curs.execute("SELECT downloaded_filename FROM downloads_temp;")+ filenames = self.curs.fetchall()+ filenames = list(sum(filenames, ()))+ return filenames- async def sql_insert_temp(self, downloaded_filename):- self.curs.execute("""INSERT OR IGNORE INTO downloads_temp VALUES (?)""", (downloaded_filename,))+ async def insert_media(self, domain: str, url_path: str, album_path: str, referrer: str, download_path: str,+ download_filename: str, original_filename: str, completed: int):+ self.curs.execute("""INSERT OR IGNORE INTO media VALUES (?, ?, ?, ?, ?, ?, ?, ?)""",+ (domain, url_path, album_path, referrer, download_path, download_filename, original_filename, completed,))self.conn.commit()- async def sql_insert_file(self, path, downloaded_filename, completed, referrer):- self.curs.execute("""INSERT OR IGNORE INTO downloads VALUES (?, ?, ?, ?)""", (path, downloaded_filename, completed, referrer, ))+ async def insert_album(self, domain: str, album_path: str, album: AlbumItem):+ if album.media:+ for media in album.media:+ if not media.complete:+ url_path = await get_db_path(media.url)+ self.curs.execute("""INSERT OR IGNORE INTO media VALUES (?, ?, ?, ?, ?, ?, ?, ?)""",+ (domain, url_path, album_path, str(media.referrer), "", "", media.filename, 0,))self.conn.commit()- async def sql_update_file(self, path, downloaded_filename, completed, referrer):- self.curs.execute("""INSERT OR REPLACE INTO downloads VALUES (?, ?, ?, ?)""", (path, downloaded_filename, completed, referrer, ))+ async def insert_cascade(self, cascade: CascadeItem):+ if not await cascade.is_empty():+ for domain, domain_obj in cascade.domains.items():+ for title, album_obj in domain_obj.albums.items():+ for media in album_obj.media:+ if not media.complete:+ url_path = media.url.path+ self.curs.execute("""INSERT OR IGNORE INTO media VALUES (?, ?, ?, ?, ?, ?, ?, ?)""",+ (domain, url_path, media.referrer.path, str(media.referrer), "",+ "", media.filename, 0,))self.conn.commit()+ async def get_downloaded_filename(self, url_path, filename):+ self.curs.execute("""SELECT download_filename FROM media WHERE url_path = ? and original_filename = ?""", (url_path, filename,))+ sql_file_check = self.curs.fetchone()+ if sql_file_check:+ return sql_file_check[0]+ return None+async def check_filename(self, filename):- self.curs.execute("""SELECT EXISTS(SELECT 1 FROM downloads WHERE downloaded_filename = ?)""", (filename, ))+ self.curs.execute("""SELECT EXISTS(SELECT 1 FROM media WHERE download_filename = ?)""", (filename, ))sql_check = self.curs.fetchone()[0]return sql_check == 1- async def get_download_filename(self, path):- self.curs.execute("""SELECT downloaded_filename FROM downloads WHERE path = ?""", (path, ))- filename = self.curs.fetchone()- if filename:- return filename[0]- return None+ async def check_existing(self, domain, url_path):+ if self.ignore_cache:+ return False+ self.curs.execute("""SELECT completed FROM media WHERE domain = ? and url_path = ?""", (domain, url_path,))+ sql_file_check = self.curs.fetchone()+ if not sql_file_check:+ return False+ return True- async def get_temp_names(self):- self.curs.execute("SELECT downloaded_filename FROM downloads_temp;")- filenames = self.curs.fetchall()- filenames = list(sum(filenames, ()))- return filenames+ async def get_existing(self, domain, url_path):+ self.curs.execute("""SELECT * FROM media WHERE domain = ? and url_path = ?""", (domain, url_path,))+ rows = self.curs.fetchall()+ return rows++ async def get_existing_album(self, domain, album_path):+ self.curs.execute("""SELECT * FROM media WHERE domain = ? and album_path = ?""", (domain, album_path,))+ rows = self.curs.fetchall()+ return rows++ async def check_complete_singular(self, domain, url_path):+ self.curs.execute("""SELECT completed FROM media WHERE domain = ? and url_path = ?""", (domain, url_path,))+ sql_file_check = self.curs.fetchone()+ if not sql_file_check:+ return False+ elif sql_file_check[0] == 0:+ return False+ else:+ return True++ async def update_pre_download(self, path: Path, filename: str, url_path: str, original_filename: str):+ self.curs.execute("""UPDATE media SET download_path = ?, download_filename = ? WHERE url_path = ? AND original_filename = ?""", (str(path), filename, url_path, original_filename,))+ self.conn.commit()++ async def mark_complete(self, url_path: str, original_filename: str):+ self.curs.execute("""UPDATE media SET completed = 1 WHERE url_path = ? AND original_filename = ?""", (url_path, original_filename,))+ self.conn.commit()++ async def sql_insert_temp(self, downloaded_filename):+ self.curs.execute("""INSERT OR IGNORE INTO downloads_temp VALUES (?)""", (downloaded_filename,))+ self.conn.commit()def exit_handler(self):+ """Exit handler on unexpected exits"""try:self.conn.commit()self.conn.close()diff --git a/cyberdrop_dl/client/client.py b/cyberdrop_dl/client/client.pyindex 207b2bf19..b3bb07977 100644--- a/cyberdrop_dl/client/client.py+++ b/cyberdrop_dl/client/client.py@@ -1,35 +1,39 @@+from __future__ import annotationsimport asyncioimport jsonimport loggingimport sslfrom pathlib import Path-import xml.etree.ElementTree as ET-from typing import Dictimport aiofilesfrom bs4 import BeautifulSoup+from rich.progress import TaskIDfrom yarl import URLimport aiohttpimport certifi-from tqdm import tqdm+from .progress_definitions import CascadeProgressfrom .rate_limiting import AsyncRateLimiter, throttle-from ..base_functions.base_functions import logger, FailureException-from ..base_functions.data_classes import FileLock+from ..base_functions.base_functions import logger+from ..base_functions.data_classes import FileLock, MediaItem+from ..base_functions.error_classes import DownloadFailureclass Client:- def __init__(self, ratelimit: int, throttle: int):+ """Creates a 'client' that can be referenced by scraping or download sessions"""+ def __init__(self, ratelimit: int, throttle: int, secure: bool):self.ratelimit = ratelimitself.throttle = throttleself.simultaneous_session_limit = asyncio.Semaphore(50)- 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.user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/109.0'self.ssl_context = ssl.create_default_context(cafile=certifi.where())+ self.verify_ssl = secureself.cookies = aiohttp.CookieJar(quote_cookie=False)-class Session:+class ScrapeSession:+ """AIOHTTP operations for scraping"""def __init__(self, client: Client) -> None:self.client = clientself.rate_limiter = AsyncRateLimiter(self.client.ratelimit)@@ -45,21 +49,6 @@ class Session:soup = BeautifulSoup(text, 'html.parser')return soup- async def get_BS4_and_url(self, url: URL):- async with self.client.simultaneous_session_limit:- 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, URL(response.url)-- async def get_text(self, url: URL):- async with self.client.simultaneous_session_limit:- 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.client.simultaneous_session_limit:async with self.rate_limiter:@@ -67,19 +56,12 @@ class Session:content = json.loads(await response.content.read())return content- async def get_xml(self, url: URL):+ async def get_text(self, url: URL):async with self.client.simultaneous_session_limit:async with self.rate_limiter:async with self.client_session.get(url, ssl=self.client.ssl_context) as response:- text = await response.content.read()- xmlTree = ET.fromstring(text)- return xmlTree-- async def get_no_resp(self, url: URL, headers: dict):- async with self.client.simultaneous_session_limit:- async with self.rate_limiter:- async with self.client_session.get(url, headers=headers, ssl=self.client.ssl_context) as response:- pass+ text = await response.text()+ return textasync def post_data_no_resp(self, url: URL, data: dict):async with self.client.simultaneous_session_limit:@@ -87,13 +69,6 @@ class Session: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.client.simultaneous_session_limit:- 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()@@ -102,69 +77,36 @@ class Session:class DownloadSession:+ """AIOHTTP operations for downloading"""def __init__(self, client: Client, conn_timeout: int):self.client = clientself.headers = {"user-agent": client.user_agent}self.timeouts = aiohttp.ClientTimeout(5*60, conn_timeout)- self.client_session = aiohttp.ClientSession(headers=self.headers, raise_for_status=True,- cookie_jar=self.client.cookies, timeout=self.timeouts)+ self.client_session = aiohttp.ClientSession(headers=self.headers, raise_for_status=True, cookie_jar=self.client.cookies, timeout=self.timeouts)self.throttle_times = {}- async def get_json_filename(self, url: URL, current_throttle: int, element: str):- headers = {'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) as resp:- json_obj = json.loads(await resp.content.read())- return json_obj[element]-- 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 get_content_type(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:- content_type = resp.headers.get('Content-Type')- return content_type.lower()-- async def download_file(self, url: URL, referer: str, current_throttle: int, range_num: str, original_filename: str,- filename: str, temp_file: str, resume_point: int, show_progress: bool,- File_Lock: FileLock, folder: Path, title: str, proxy: str, headers: Dict):- headers['Referer'] = referer+ async def download_file(self, media: MediaItem, file: Path, current_throttle: int, resume_point: int,+ File_Lock: FileLock, proxy: str, headers: dict, original_filename: str,+ progress: CascadeProgress, file_task: TaskID):+ headers['Referer'] = str(media.referrer)headers['user-agent'] = self.client.user_agent- if range_num:- headers['Range'] = range_num- await throttle(self, current_throttle, url.host)- async with self.client_session.get(url, headers=headers, ssl=self.client.ssl_context,+ await throttle(self, current_throttle, media.url.host)+ async with self.client_session.get(media.url, headers=headers, ssl=self.client.ssl_context,raise_for_status=True, proxy=proxy) 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 experiencing issues, or you are being ratelimited", str(url))- logger.debug("Content received: " + content_type.lower())+ logger.debug("Server for %s is experiencing issues, you are being ratelimited, or cookies have expired", str(media.url))await File_Lock.remove_lock(original_filename)- raise FailureException(code=resp.status, message="Unexpectedly got text as response", rescrape=True)+ raise DownloadFailure(code=resp.status, message="Unexpectedly got text as response")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))+ file.parent.mkdir(parents=True, exist_ok=True)++ progress.update(file_task, total=total)+ progress.advance(file_task, resume_point)++ async with aiofiles.open(file, mode='ab') as f:+ async for chunk, _ in resp.content.iter_chunks():+ await asyncio.sleep(0)+ await f.write(chunk)+ progress.advance(file_task, len(chunk))diff --git a/cyberdrop_dl/client/downloaders.py b/cyberdrop_dl/client/downloaders.pyindex 03f52e6cf..cf58a7099 100644--- a/cyberdrop_dl/client/downloaders.py+++ b/cyberdrop_dl/client/downloaders.py@@ -1,23 +1,23 @@+from __future__ import annotations+import asyncioimport logging+import multiprocessingfrom base64 import b64encodefrom functools import wraps-from typing import List, Tuple, Dictfrom random import gauss-import aiofiles-import aiofiles.osimport aiohttp.client_exceptions-from colorama import Fore-from tqdm import tqdm+from rich.progress import TaskIDfrom yarl import URL-from ..base_functions.base_functions import FILE_FORMATS, MAX_FILENAME_LENGTH, log, logger, sanitize, FailureException, \- is_forum, check_free_space+from .progress_definitions import CascadeProgress, ForumsProgress+from ..base_functions.base_functions import log, logger, check_free_space, allowed_filetype, get_db_path+from ..base_functions.error_classes import DownloadFailurefrom ..base_functions.sql_helper import SQLHelper-from ..base_functions.data_classes import AlbumItem, CascadeItem, FileLock+from ..base_functions.data_classes import AlbumItem, CascadeItem, FileLock, ForumItem, DomainItem, MediaItemfrom ..client.client import Client, DownloadSession-from ..scraper.scraper_helper import ScrapeMapper+from ..scraper.Scraper import ScrapeMapperasync def basic_auth(username, password):@@ -31,345 +31,269 @@ def retry(f):while True:try:return await f(self, *args, **kwargs)- except FailureException as e:+ except DownloadFailure as e:if not self.disable_attempt_limit:+ # TODO ALL THIS BELOWif self.current_attempt[args[0].parts[-1]] >= self.attempts - 1:logger.debug('Skipping %s...', args[0])raise+ logger.debug(e)logger.debug(f'Retrying ({self.current_attempt[args[0].parts[-1]]}) {args[0]}...')self.current_attempt[args[0].parts[-1]] += 1- if e.rescrape:- link = await self.album_obj.get_referrer(URL(args[0]))- await log("Attempting rescrape for " + str(args[0]), quiet=True)-- async with asyncio.Semaphore(1):- await self.backup_scraper.map_url(link)- content_object = self.backup_scraper.Cascade- self.backup_scraper.Cascade = CascadeItem({})-- if not await content_object.is_empty():- link_pairs = []- for domain in content_object.domains.keys():- for album in content_object.domains[domain].albums.keys():- link_pairs = content_object.domains[domain].albums[album].link_pairs- url_map = await self.album_obj.replace_link_pairs(link_pairs)- replaced_link = url_map[args[0]]- args = list(args)- args[0] = replaced_link- args = tuple(args)- else:- raise-- elif 'cyberdrop' in args[0].host:- ext = '.' + args[0].name.split('.')[-1]- if ext in FILE_FORMATS['Images']:- args = list(args)- args[0] = args[0].with_host('img-01.cyberdrop.to')- args = tuple(args)await asyncio.sleep(2)return wrapper+class Files:+ def __init__(self):+ self.completed_files = 0+ self.skipped_files = 0+ self.failed_files = 0++class Downloader:- def __init__(self, album_obj: AlbumItem, title: str, max_workers: int, excludes: Dict[str, bool],- SQL_helper: SQLHelper, client: Client, file_args: Dict, runtime_args: Dict, pixeldrain_api_key: str,- scraper: ScrapeMapper):- self.album_obj = album_obj+ def __init__(self, args: dict, client: Client, SQL_Helper: SQLHelper, scraper: ScrapeMapper, max_workers: int,+ domain: str, domain_obj: DomainItem, semaphore: asyncio.Semaphore, files: Files):+ self.backup_scraper = scraperself.client = client- self.folder = file_args['output_folder']- self.title = title-- self.SQL_helper = SQL_helper+ self.download_session = DownloadSession(client, args["Ratelimiting"]["connection_timeout"])self.File_Lock = FileLock()+ self.SQL_Helper = SQL_Helper- self.attempts = runtime_args['attempts']- self.current_attempt = {}- self.disable_attempt_limit = runtime_args['disable_attempt_limit']- self.mark_downloaded = runtime_args['mark_downloaded']+ self.domain = domain+ self.domain_obj = domain_obj- self.excludes = excludes+ self.files = files+ self.current_attempt = {}self.max_workers = max_workers- self._semaphore = asyncio.Semaphore(max_workers)+ self._semaphore = semaphoreself.delay = {'cyberfile.is': 1, 'anonfiles.com': 1}- self.proxy = runtime_args['proxy']- self.pixeldrain_api_key = pixeldrain_api_key-- self.backup_scraper = scraper-- self.runtime_args = runtime_args- self.file_args = file_args-+ self.pixeldrain_api_key = args["Authentication"]["pixeldrain_api_key"]++ self.ignore_history = args["Ignore"]["ignore_history"]+ self.exclude_audio = args["Ignore"]["exclude_audio"]+ self.exclude_images = args["Ignore"]["exclude_images"]+ self.exclude_videos = args["Ignore"]["exclude_videos"]+ self.exclude_other = args["Ignore"]["exclude_other"]++ self.allowed_attempts = args["Runtime"]["attempts"]+ self.allow_insecure_connections = args["Runtime"]["allow_insecure_connections"]+ self.disable_attempt_limit = args["Runtime"]["disable_attempt_limit"]+ self.download_dir = args["Files"]["output_folder"]+ self.mark_downloaded = args["Runtime"]["mark_downloaded"]+ self.proxy = args["Runtime"]["proxy"]+ self.required_free_space = args["Runtime"]["required_free_space"]++ async def start_domain(self, progress: CascadeProgress, cascade_task: TaskID):+ domain_task = progress.add_task("[light_pink3]"+self.domain.upper(), progress_type="domain", total=len(self.domain_obj.albums))+ for album, album_obj in self.domain_obj.albums.items():+ await self.start_album(progress, domain_task, album, album_obj)+ progress.advance(cascade_task, 1)+ progress.update(domain_task, visible=False)+ progress.update(domain_task, total=len(self.domain_obj.albums), completed=len(self.domain_obj.albums))++ async def start_album(self, progress: CascadeProgress, domain_task: TaskID, album: str, album_obj: AlbumItem):+ album_task = progress.add_task("[pink3]"+album.upper().split("/")[-1], progress_type="album", total=len(album_obj.media))+ download_tasks = []+ for media in album_obj.media:+ download_tasks.append(self.start_file(progress, album_task, album, media))+ await asyncio.gather(*download_tasks)+ progress.update(album_task, visible=False)+ progress.advance(domain_task, 1)++ async def start_file(self, progress: CascadeProgress, album_task: TaskID, album: str, media: MediaItem):+ async with self._semaphore:+ await self.download_file(progress, album_task, album, media)@retry- async def download_file(self, url: URL, referral: URL, filename: str, session: DownloadSession, db_path: str,- show_progress: bool = True) -> None:- """Download the content of given URL"""- if not await check_free_space(self.runtime_args['required_free_space'], self.file_args['output_folder']):- await log("Not enough free space to download file, skipping.", quiet=True)+ async def download_file(self, progress: CascadeProgress, album_task: TaskID, album: str, media: MediaItem):+ if media.complete:+ await log(f"Previously Downloaded: {media.filename}", quiet=True)+ self.files.skipped_files += 1+ progress.advance(album_task, 1)return- if url.parts[-1] not in self.current_attempt:- self.current_attempt[url.parts[-1]] = 0+ if not await check_free_space(self.required_free_space, self.download_dir):+ await log("We've run out of free space.", quiet=True)+ self.files.skipped_files += 1+ progress.advance(album_task, 1)+ return- referer = str(referral)- current_throttle = self.client.throttle+ if not await allowed_filetype(media, self.exclude_images, self.exclude_videos, self.exclude_audio, self.exclude_other):+ await log(f"Blocked by file extension: {media.filename}", quiet=True)+ self.files.skipped_files += 1+ progress.advance(album_task, 1)+ return- while await self.File_Lock.check_lock(filename):+ while await self.File_Lock.check_lock(media.filename):await asyncio.sleep(gauss(1, 1.5))- await self.File_Lock.add_lock(filename)-- try:- async with self._semaphore:- # Make suffix always lower case- original_filename = filename- ext = '.' + filename.split('.')[-1]-- complete_file = (self.folder / self.title / filename)- partial_file = complete_file.with_suffix(complete_file.suffix + '.part')-- if complete_file.exists() or partial_file.exists():- if complete_file.exists():- total_size = await 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, referer)- logger.debug("\nFile already exists and matches expected size: " + str(complete_file))- await self.File_Lock.remove_lock(original_filename)- return-- download_name = await self.SQL_helper.get_download_filename(db_path)- iterations = 1+ await self.File_Lock.add_lock(media.filename)- if not download_name:- while True:- filename = f"{complete_file.stem} ({iterations}){ext}"- iterations += 1- temp_complete_file = (self.folder / self.title / filename)- if not temp_complete_file.exists():- if not await self.SQL_helper.check_filename(filename):- break- else:- filename = download_name+ if media.url.parts[-1] not in self.current_attempt:+ self.current_attempt[media.url.parts[-1]] = 0- await self.SQL_helper.sql_insert_file(db_path, filename, 0, referer)+ current_throttle = self.client.throttle+ url_path = await get_db_path(URL(media.url))- if self.mark_downloaded:- await self.SQL_helper.sql_update_file(db_path, filename, 1, referer)- return+ original_filename = media.filename+ complete_file = (self.download_dir / album / media.filename)+ partial_file = complete_file.with_suffix(complete_file.suffix + '.part')- complete_file = (self.folder / self.title / filename)- temp_file = complete_file.with_suffix(complete_file.suffix + '.part')- resume_point = 0+ while True:+ if complete_file.exists() or partial_file.exists():+ downloaded_filename = await self.SQL_Helper.get_downloaded_filename(url_path, original_filename)+ if downloaded_filename:+ if media.filename == downloaded_filename:+ if complete_file.exists():+ await log(f"Previously Downloaded: {media.filename}", quiet=True)+ self.files.skipped_files += 1+ await self.SQL_Helper.mark_complete(url_path, original_filename)+ progress.advance(album_task, 1)+ return+ else:+ break+ else:+ media.filename = downloaded_filename+ complete_file = (self.download_dir / album / media.filename)+ partial_file = complete_file.with_suffix(complete_file.suffix + '.part')+ continue+ else:+ iterations = 1+ while True:+ filename = f"{complete_file.stem} ({iterations}){media.ext}"+ iterations += 1+ temp_complete_file = (self.download_dir / album / filename)+ if not temp_complete_file.exists():+ if not await self.SQL_Helper.check_filename(filename):+ media.filename = filename+ complete_file = (self.download_dir / album / media.filename)+ partial_file = complete_file.with_suffix(complete_file.suffix + '.part')+ break+ break+ else:+ break- await self.SQL_helper.sql_insert_temp(str(temp_file))+ await self.SQL_Helper.update_pre_download(complete_file, media.filename, url_path, original_filename)- range_num = None- if temp_file.exists():- resume_point = temp_file.stat().st_size- range_num = f'bytes={resume_point}-'+ if self.mark_downloaded:+ await self.SQL_Helper.mark_complete(url_path, original_filename)- for key, value in self.delay.items():- if key in url.host:- current_throttle = value+ resume_point = 0+ await self.SQL_Helper.sql_insert_temp(str(partial_file))+ range_num = None+ if partial_file.exists():+ resume_point = partial_file.stat().st_size+ range_num = f'bytes={resume_point}-'- headers = {"Authorization": await basic_auth("Cyberdrop-DL", self.pixeldrain_api_key)} \- if (self.pixeldrain_api_key and "pixeldrain" in url.host) else {}+ for key, value in self.delay.items():+ if key in media.url.host:+ current_throttle = value- await session.download_file(url, referer, current_throttle, range_num, original_filename, filename,- temp_file, resume_point, show_progress, self.File_Lock, self.folder,- self.title, self.proxy, headers)+ headers = {"Authorization": await basic_auth("Cyberdrop-DL", self.pixeldrain_api_key)} \+ if (self.pixeldrain_api_key and "pixeldrain" in media.url.host) else {}+ if range_num:+ headers['Range'] = range_num- await self.rename_file(filename, url, db_path, referer)+ try:+ task_description = media.filename+ if len(task_description) >= 40:+ task_description = task_description[:37] + "..."+ else:+ task_description = task_description.rjust(40)+ file_task = progress.add_task("[plum3]"+task_description, progress_type="file")+ await self.download_session.download_file(media, partial_file, current_throttle, resume_point,+ self.File_Lock, self.proxy, headers, original_filename,+ progress, file_task)+ partial_file.rename(complete_file)+ await self.SQL_Helper.mark_complete(url_path, original_filename)+ if media.url.parts[-1] in self.current_attempt.keys():+ self.current_attempt.pop(media.url.parts[-1])+ self.files.completed_files += 1+ progress.advance(album_task, 1)+ progress.update(file_task, visible=False)+ await log(f"Completed Download: {media.filename}", quiet=True)await self.File_Lock.remove_lock(original_filename)except (aiohttp.client_exceptions.ClientPayloadError, aiohttp.client_exceptions.ClientOSError,aiohttp.client_exceptions.ServerDisconnectedError, asyncio.TimeoutError,- aiohttp.client_exceptions.ClientResponseError, FailureException) as e:+ aiohttp.client_exceptions.ClientResponseError, DownloadFailure) as e:if await self.File_Lock.check_lock(original_filename):await self.File_Lock.remove_lock(original_filename)+ new_error = DownloadFailure(1)+ try:+ progress.update(file_task, visible=False)+ except:+ pass+if hasattr(e, "message"):- logging.debug(f"\n{url} ({e.message})")+ logging.debug(f"\n{media.url} ({e.message})")+ new_error.message = e.messageif hasattr(e, "code"):if 400 <= e.code < 500 and e.code != 429:logger.debug("We ran into a 400 level error: %s", str(e.code))+ await log(f"Failed Download: {media.filename}", quiet=True)+ self.files.failed_files += 1+ progress.advance(album_task, 1)+ if media.url.parts[-1] in self.current_attempt.keys():+ self.current_attempt.pop(media.url.parts[-1])returnlogger.debug("Error status code: " + str(e.code))+ new_error.code = e.code++ raise new_error+++async def download_cascade(args: dict, Cascade: CascadeItem, SQL_Helper: SQLHelper, client: Client,+ scraper: ScrapeMapper) -> None:+ user_threads = args["Runtime"]["simultaneous_downloads"]+ files = Files()++ with CascadeProgress() as progress:+ cascade_task = progress.add_task("[light_salmon3]Domains", progress_type="cascade", total=len(Cascade.domains))++ downloaders = []+ tasks = []+ for domain, domain_obj in Cascade.domains.items():+ threads = user_threads if user_threads != 0 else multiprocessing.cpu_count()+ if 'bunkr' in domain or 'pixeldrain' in domain or 'anonfiles' in domain:+ threads = 2 if (threads > 2) else threads+ download_semaphore = asyncio.Semaphore(threads)+ downloaders.append(Downloader(args, client, SQL_Helper, scraper, threads, domain, domain_obj, download_semaphore, files))+ for downloader in downloaders:+ tasks.append(downloader.start_domain(progress, cascade_task))+ await asyncio.gather(*tasks)++ await log(f"| [green]Files Complete: {files.completed_files}[/green] - [yellow]Files Skipped: {files.skipped_files}[/yellow] - [red]Files Failed: {files.failed_files}[/red] |")+++async def download_forums(args: dict, Forums: ForumItem, SQL_Helper: SQLHelper, client: Client,+ scraper: ScrapeMapper) -> None:+ user_threads = args["Runtime"]["simultaneous_downloads"]+ files = Files()++ with ForumsProgress() as progress:+ forum_task = progress.add_task("[orange3]FORUM THREADS", progress_type="forum", total=len(Forums.threads))+ for title, Cascade in Forums.threads.items():+ cascade_task = progress.add_task("[light_salmon3]"+title.upper(), progress_type="cascade", total=len(Cascade.domains))++ downloaders = []+ tasks = []+ for domain, domain_obj in Cascade.domains.items():+ threads = user_threads if user_threads != 0 else multiprocessing.cpu_count()+ if 'bunkr' in domain or 'pixeldrain' in domain or 'anonfiles' in domain:+ threads = 2 if (threads > 2) else threads+ download_semaphore = asyncio.Semaphore(threads)+ downloaders.append(Downloader(args, client, SQL_Helper, scraper, threads, domain, domain_obj, download_semaphore, files))+ for downloader in downloaders:+ tasks.append(downloader.start_domain(progress, cascade_task))+ await asyncio.gather(*tasks)++ progress.advance(forum_task, 1)+ await log("")+ await log(f"| [green]Files Complete: {files.completed_files}[/green] - [yellow]Files Skipped: {files.skipped_files}[/yellow] - [red]Files Failed: {files.failed_files}[/red] |")- if e.__class__.__name__ == 'FailureException':- if await is_forum(referral):- return- raise FailureException(code=e.code, message=e.message, rescrape=e.rescrape)- else:- raise FailureException(code=1, message=e)-- async def rename_file(self, filename: str, url: URL, db_path: str, referer: str) -> None:- """Rename complete file."""- complete_file = (self.folder / self.title / filename)- temp_file = complete_file.with_suffix(complete_file.suffix + '.part')- if complete_file.exists():- logger.debug(str(self.folder / self.title / filename) + " Already Exists")- await aiofiles.os.remove(temp_file)- else:- temp_file.rename(complete_file)-- await self.SQL_helper.sql_update_file(db_path, filename, 1, referer)- if url.parts[-1] in self.current_attempt.keys():- self.current_attempt.pop(url.parts[-1])- logger.debug("Finished " + filename)-- async def get_filename(self, url: URL, referral: URL, session: DownloadSession):- """Does all the necessary work to try and figure out what exactly the Filename should be."""- referer = str(referral)-- filename = url.name- if hasattr(url, "query_string"):- query_str = url.query_string- ext = '.' + query_str.split('.')[-1].lower()- if await self.check_include(ext):- filename = query_str.split("=")[-1]- filename = await sanitize(filename)- if "v=" in filename:- filename = filename.split('v=')[0]- if len(filename) > MAX_FILENAME_LENGTH:- fileext = filename.split('.')[-1]- filename = filename[:MAX_FILENAME_LENGTH] + '.' + fileext-- ext = '.' + filename.split('.')[-1].lower()- current_throttle = self.client.throttle- if not await self.check_include(ext):- for key, value in self.delay.items():- if key in url.host:- if value > current_throttle:- current_throttle = value- try:- if "pixeldrain" in url.host:- filename = await session.get_json_filename(url.with_query(None) / "info", current_throttle, 'name')- else:- filename = await session.get_filename(url, referer, current_throttle)- filename = await sanitize(filename)- ext = '.' + filename.split('.')[-1].lower()- if not await self.check_include(ext):- logging.debug("No file extension on content in link: " + str(url))- raise FailureException(0)- except FailureException:- try:- content_type = await session.get_content_type(url, referer, current_throttle)- if "image" in content_type:- ext_temp = content_type.split('/')[-1]- filename = filename + '.' + ext_temp- filename = await sanitize(filename)- else:- logging.debug("\nUnhandled content_type for checking filename: " + content_type)- raise FailureException(0)- except FailureException:- await log("\nCouldn't get filename for: " + str(url))- raise FailureException(0)-- ext = '.' + filename.split('.')[-1].lower()- filename = filename.replace('.' + filename.split('.')[-1], ext)- return filename-- async def check_exclude(self, filename):- """Check the exclude arguments to see if this file should be skipped (False)."""- ext = '.' + filename.split('.')[-1]- if self.excludes['videos']:- if ext in FILE_FORMATS['Videos']:- logging.debug("Skipping " + filename)- return False- if self.excludes['images']:- if ext in FILE_FORMATS['Images']:- logging.debug("Skipping " + filename)- return False- if self.excludes['audio']:- if ext in FILE_FORMATS['Audio']:- logging.debug("Skipping " + filename)- return False- if self.excludes['other']:- if ext in FILE_FORMATS['Other']:- logging.debug("Skipping " + filename)- return False- return True-- async def check_include(self, ext):- if (ext in FILE_FORMATS['Images'] or ext in FILE_FORMATS['Videos']- or ext in FILE_FORMATS['Audio'] or ext in FILE_FORMATS['Other']):- return True-- async def get_db_path(self, url: URL):- db_path = url.path- if 'anonfiles' in url.host or 'bayfiles' in url.host:- db_path = db_path.split('/')- db_path.pop(0)- db_path.pop(1)- db_path = '/' + '/'.join(db_path)- return db_path-- 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-- logger.debug("Working on " + str(url))-- db_path = await self.get_db_path(url)-- # return if completed already- if await self.SQL_helper.sql_check_existing(db_path):- if url.parts[-1] in self.current_attempt.keys():- self.current_attempt.pop(url.parts[-1])- logger.debug(msg=f"{db_path} found in DB: Skipping {db_path}")- return-- try:- filename = await self.get_filename(url, referral, session)- if await self.check_exclude(filename):- await self.download_file(url, referral=referral, filename=filename, session=session, db_path=db_path,- show_progress=show_progress)- except Exception as e:- if hasattr(e, "rescrape"):- if url.parts[-1] in self.current_attempt.keys():- if not (self.current_attempt[url.parts[-1]] >= self.attempts - 1) and e.rescrape:- return- if url.parts[-1] in self.current_attempt.keys():- self.current_attempt.pop(url.parts[-1])- logging.debug(e)- await log(f"\nError attempting {url}")- if hasattr(e, "message"):- logging.debug(f"\n{url} ({e.message})")- if hasattr(e, "code"):- logger.debug("Error status code: " + str(e.code))-- async def download_content(self, show_progress: bool = True, conn_timeout: int = 15) -> None:- """Download the content of all links and save them as files."""- session = DownloadSession(self.client, conn_timeout)- if not await check_free_space(self.runtime_args['required_free_space'], self.file_args['output_folder']):- await log("Not enough free space to run the program.", Fore.RED)- exit(0)- coros = [self.download_and_store(url_object, session, show_progress)- for url_object in self.album_obj.link_pairs]- for func in tqdm(asyncio.as_completed(coros), total=len(coros), desc=self.title, unit='FILE'):- await func- await session.client_session.close()- self.SQL_helper.conn.commit()---async def get_downloaders(Cascade: CascadeItem, excludes: Dict[str, bool], SQL_helper: SQLHelper, client: Client,- max_workers: int, file_args: Dict, runtime_args: Dict, pixeldrain_api_key: str,- scraper: ScrapeMapper) -> List[Downloader]:- """Get a list of downloader objects to run."""- downloaders = []-- for domain, domain_obj in Cascade.domains.items():- max_workers_temp = max_workers- if 'bunkr' in domain or 'pixeldrain' in domain or 'anonfiles' in domain:- max_workers_temp = 2 if (max_workers > 2) else max_workers- for title, album_obj in domain_obj.albums.items():- downloader = Downloader(album_obj, title=title, max_workers=max_workers_temp, excludes=excludes,- SQL_helper=SQL_helper, client=client, file_args=file_args,- runtime_args=runtime_args, pixeldrain_api_key=pixeldrain_api_key,- scraper=scraper)- downloaders.append(downloader)- return downloadersdiff --git a/cyberdrop_dl/client/progress_definitions.py b/cyberdrop_dl/client/progress_definitions.pynew file mode 100644index 000000000..d8edb01c0--- /dev/null+++ b/cyberdrop_dl/client/progress_definitions.py@@ -0,0 +1,101 @@+from rich.progress import Progress, BarColumn, TimeRemainingColumn, TextColumn, SpinnerColumn, TransferSpeedColumn, \+ FileSizeColumn, TotalFileSizeColumn, DownloadColumn+++class CascadeProgress(Progress):+ def get_renderables(self):+ for task in self.tasks:+ if task.fields.get("progress_type") == "cascade":+ self.columns = (+ "{task.completed} of {task.total} Domains Completed",+ BarColumn(),+ "[progress.percentage]{task.percentage:>3.2f}%"+ )+ if task.fields.get("progress_type") == "domain":+ self.columns = (+ "├─",+ "[progress.description]{task.description}",+ BarColumn(),+ "[progress.percentage]{task.percentage:>3.2f}%",+ "{task.completed} of {task.total} Albums Completed"+ )+ if task.fields.get("progress_type") == "domain_summary":+ self.columns = (+ "├─",+ "[progress.description]{task.description}",+ "{task.completed} of {task.total} Albums Completed"+ )+ if task.fields.get("progress_type") == "album":+ self.columns = (+ "├──",+ "[progress.description]{task.description}",+ BarColumn(),+ "[progress.percentage]{task.percentage:>3.2f}%",+ "{task.completed} of {task.total} Files Completed"+ )+ if task.fields.get("progress_type") == "file":+ self.columns = (+ "├───", SpinnerColumn(),+ "[progress.description]{task.description}",+ BarColumn(),+ "[progress.percentage]{task.percentage:>3.2f}%",+ "•",+ DownloadColumn(),+ "•",+ TransferSpeedColumn()+ )+ yield self.make_tasks_table([task])+++class ForumsProgress(Progress):+ def get_renderables(self):+ for task in self.tasks:+ if task.fields.get("progress_type") == "forum":+ self.columns = (+ "[progress.description]{task.description}",+ BarColumn(bar_width=None),+ "[progress.percentage]{task.percentage:>3.2f}%",+ "{task.completed} of {task.total} Threads Completed",+ )+ if task.fields.get("progress_type") == "cascade":+ self.columns = (+ "├─",+ "[progress.description]{task.description}",+ BarColumn(bar_width=None),+ "[progress.percentage]{task.percentage:>3.2f}%",+ "{task.completed} of {task.total} Domains Completed",+ )+ if task.fields.get("progress_type") == "domain":+ self.columns = (+ "├──",+ "[progress.description]{task.description}",+ BarColumn(bar_width=None),+ "[progress.percentage]{task.percentage:>3.2f}%",+ "{task.completed} of {task.total} Albums Completed",+ )+ if task.fields.get("domain_updated"):+ self.columns = (+ "├──",+ "[progress.description]{task.description}",+ "{task.completed} of {task.total} Albums Completed",+ )+ if task.fields.get("progress_type") == "album":+ self.columns = (+ "├───",+ "[progress.description]{task.description}",+ BarColumn(bar_width=None),+ "[progress.percentage]{task.percentage:>3.2f}%",+ "{task.completed} of {task.total} Files Completed",+ )+ if task.fields.get("progress_type") == "file":+ self.columns = (+ "├────", SpinnerColumn(),+ "[progress.description]{task.description}",+ BarColumn(bar_width=None),+ "[progress.percentage]{task.percentage:>3.2f}%",+ "•",+ DownloadColumn(),+ "•",+ TransferSpeedColumn()+ )+ yield self.make_tasks_table([task])diff --git a/cyberdrop_dl/client/rate_limiting.py b/cyberdrop_dl/client/rate_limiting.pyindex 976287c3d..99cb16886 100644--- a/cyberdrop_dl/client/rate_limiting.py+++ b/cyberdrop_dl/client/rate_limiting.py@@ -10,9 +10,7 @@ from ..base_functions.base_functions import loggerclass AsyncRateLimiter:- """- Provides rate limiting for an operation with a configurable number of requests for a time period.- """+ """Provides rate limiting for an operation with a configurable number of requests for a time period."""__lock: asyncio.Lockcallback: Optional[Callable[[float], Awaitable[Any]]]@@ -67,6 +65,7 @@ class AsyncRateLimiter:async def throttle(self, delay: int, host: str) -> None:+ """Throttles requests to domains by a parameter amount of time"""if delay is None or delay == 0:return@@ -83,7 +82,4 @@ async def throttle(self, delay: int, host: str) -> None:returnremaining = delay - elapsed + 0.25-- log_string = f'\nDelaying request to {host} for {remaining:.2f} seconds.'- # logger.debug(log_string)await asyncio.sleep(remaining)diff --git a/cyberdrop_dl/crawlers/Anonfiles_Spider.py b/cyberdrop_dl/crawlers/Anonfiles_Spider.pyindex 195652a0b..79a42261b 100644--- a/cyberdrop_dl/crawlers/Anonfiles_Spider.py+++ b/cyberdrop_dl/crawlers/Anonfiles_Spider.py@@ -1,33 +1,49 @@from yarl import URL-from ..base_functions.base_functions import log, logger-from ..base_functions.data_classes import DomainItem-from ..client.client import Session+from ..base_functions.base_functions import log, logger, get_filename_and_ext, get_db_path+from ..base_functions.data_classes import MediaItem, AlbumItem+from ..base_functions.sql_helper import SQLHelper+from ..client.client import ScrapeSessionclass AnonfilesCrawler:- def __init__(self, *, include_id=False, quiet: bool):- self.include_id = include_id+ def __init__(self, quiet: bool, SQL_Helper: SQLHelper):self.quiet = quiet+ self.SQL_Helper = SQL_Helper+ self.api_link = URL("https://api.anonfiles.com/v2/file")- async def fetch(self, session: Session, url: URL):- domain_obj = DomainItem(url.host, {})+ async def fetch(self, session: ScrapeSession, url: URL):+ if 'cdn' in url.host:+ url = URL("https://anonfiles.com") / url.parts[1]- await log("Starting scrape of " + str(url), quiet=self.quiet)+ album_obj = AlbumItem("Anon Loose Files", [])++ await log(f"[green]Starting: {str(url)}[/green]", quiet=self.quiet)try:- soup = await session.get_BS4(url)+ json = await session.get_json(self.api_link/url.parts[1]/"info")+ if json['status']:+ soup = await session.get_BS4(url)++ link = soup.select_one("a[id=download-url]")+ link = URL(link.get('href'))- title = "Anon Loose Files"- link = soup.select_one("a[id=download-url]")- link = URL(link.get('href'))- await domain_obj.add_to_album(title, link, url)+ url_path = await get_db_path(link)+ complete = await self.SQL_Helper.check_complete_singular("anonfiles", url_path)++ filename, ext = await get_filename_and_ext(".".join(json['data']['file']['metadata']['name'].rsplit("_", 1)))+ media_item = MediaItem(link, url, complete, filename, ext)+ await album_obj.add_media(media_item)+ if not complete:+ await self.SQL_Helper.insert_media("anonfiles", url_path, "", str(url), "", "", filename, 0)+ else:+ await log(f"[red]Dead: {str(url)}[/red]", quiet=self.quiet)except Exception as e:logger.debug("Error encountered while handling %s", str(url), exc_info=True)- await log("Error scraping " + str(url), quiet=self.quiet)+ await log(f"[red]Error: {str(url)}[/red]", quiet=self.quiet)logger.debug(e)+ return album_obj- await log("Finished scrape of " + str(url), quiet=self.quiet)-- return domain_obj+ await log(f"[green]Finished: {str(url)}[/green]", quiet=self.quiet)+ return album_objdiff --git a/cyberdrop_dl/crawlers/Bunkr_Spider.py b/cyberdrop_dl/crawlers/Bunkr_Spider.pyindex f19919936..9fc787753 100644--- a/cyberdrop_dl/crawlers/Bunkr_Spider.py+++ b/cyberdrop_dl/crawlers/Bunkr_Spider.py@@ -1,101 +1,138 @@import jsonimport re+from pathlib import Pathfrom 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+from ..base_functions.base_functions import log, logger, make_title_safe, FILE_FORMATS, get_filename_and_ext+from ..base_functions.data_classes import AlbumItem, MediaItem+from ..base_functions.error_classes import NoExtensionFailure+from ..base_functions.sql_helper import SQLHelper+from ..client.client import ScrapeSessionclass BunkrCrawler:- def __init__(self, *, include_id=False, quiet: bool):- self.include_id = include_id+ def __init__(self, quiet: bool, SQL_Helper: SQLHelper):self.quiet = quiet+ self.SQL_Helper = SQL_Helper- async def fetch(self, session: Session, url: URL):- domain_obj = DomainItem(url.host, {})+ async def fetch(self, session: ScrapeSession, url: URL):+ album_obj = AlbumItem("Bunkr Loose Items", [])- cdn_possibilities = r"(?:cdn.bunkr...|cdn..bunkr...|cdn...bunkr...)"- ext = '.' + str(url).split('.')[-1]- ext = ext.lower()+ cdn_possibilities = r"(?:cdn.bunkr...|cdn..bunkr...|cdn...bunkr...|media-files.bunkr...|media-files..bunkr...|media-files...bunkr...)"+ ext = '.' + url.parts[-1].split('.')[-1]+ if ext:+ ext = ext.lower()if ext in FILE_FORMATS['Videos']:- url = URL(re.sub(cdn_possibilities, "stream.bunkr.ru/v", str(url)))- if ext in FILE_FORMATS['Other']:- url = URL(re.sub(cdn_possibilities, "files.bunkr.ru/d", str(url)))- if ext in FILE_FORMATS['Images']:+ url = URL(re.sub(cdn_possibilities, "stream.bunkr.su/v", str(url)))+ elif ext in FILE_FORMATS['Images']:+ await log(f"[green]Starting: {str(url)}[/green]", quiet=self.quiet)++ check_complete = await self.SQL_Helper.check_complete_singular("bunkr", url.path)url = URL(str(url).replace("https://cdn", "https://i"))- if await check_direct(url):- await domain_obj.add_to_album(link=url, referral=url, title="Bunkr Loose Files")- return domain_obj+ filename, ext = await get_filename_and_ext(url.name)+ media_item = MediaItem(url, url, check_complete, filename, ext)+ await album_obj.add_media(media_item)+ await self.SQL_Helper.insert_album("bunkr", url.path, album_obj)+ await log(f"[green]Finished: {str(url)}[/green]", quiet=self.quiet)+ return album_obj+ elif ext:+ url = URL(re.sub(cdn_possibilities, "files.bunkr.su/d", str(url)))++ await log(f"[green]Starting: {str(url)}[/green]", quiet=self.quiet)if "stream.bunkr." in url.host or "files.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), quiet=self.quiet)- return domain_obj+ media = await self.get_file(session, url)+ if not media.filename:+ return album_obj+ await album_obj.add_media(media)+ await log(f"[green]Finished: {str(url)}[/green]", quiet=self.quiet)+ if not media.complete:+ await self.SQL_Helper.insert_media("bunkr", media.url.path, "", str(url), "", "", media.filename, 0)+ return album_obj- await log("Starting scrape of " + str(url), quiet=self.quiet)+ album_obj = await self.get_album(session, url)+ await self.SQL_Helper.insert_album("bunkr", url.path, album_obj)+ if album_obj.media:+ await log(f"[green]Finished: {str(url)}[/green]", quiet=self.quiet)+ return album_obj++ async def get_file(self, session: ScrapeSession, url: URL):try:soup = await session.get_BS4(url)- build_id = json.loads(soup.select_one("script[id=__NEXT_DATA__]").get_text())- try:- files = build_id['props']['pageProps']['album']['files']- json_obj = build_id['props']['pageProps']- except KeyError:- 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['album']['files']:- ext = '.' + file['name'].split('.')[-1].lower()- referrer = URL+ json_obj = json.loads(soup.select_one("script[id=__NEXT_DATA__]").get_text())++ # json_fetch = URL("https://" + url.host + "/_next/data/" + build_id + url.path + '.json')+ # json_obj = await session.get_json(json_fetch)+ # link = URL(json_obj['pageProps']['file']['mediafiles'] + '/' + json_obj['pageProps']['file']['name'])++ json_obj = json_obj['props']+ filename, ext = await get_filename_and_ext(json_obj['pageProps']['file']['name'])+ link = URL(json_obj['pageProps']['file']['mediafiles'] + '/' + json_obj['pageProps']['file']['name'])+ complete = await self.SQL_Helper.check_complete_singular("bunkr", link.path)+ if complete:+ media = MediaItem(link, url, True, filename, ext)+ return media+ media = MediaItem(link, url, False, filename, ext)+ return media++ except Exception as e:+ logger.debug("Error encountered while handling %s", str(url), exc_info=True)+ await log(f"[red]Error: {str(url)}[/red]", quiet=self.quiet)+ logger.debug(e)+ return MediaItem(url, url, False, "", "")++ async def get_album(self, session: ScrapeSession, url: URL):+ try:+ existing = await self.SQL_Helper.get_existing_album("bunkr", url.path)+ completed_files = []+ album = AlbumItem(url.name, [])+ if existing:+ title = Path(existing[0][-4]).name+ await album.set_new_title(title)+ for file in existing:+ if file[-1] == 1:+ completed_files.append(file[-2])++ soup = await session.get_BS4(url)+ json_obj = json.loads(soup.select_one("script[id=__NEXT_DATA__]").get_text())+ json_obj = json_obj['props']+ title = await make_title_safe(json_obj['pageProps']['album']['name'])+ await album.set_new_title(title)+ for file in json_obj['pageProps']['album']['files']:+ try:+ filename, ext = await get_filename_and_ext(file['name'])+ except NoExtensionFailure:+ continue+if ext in FILE_FORMATS['Videos']:cdn_loc = file['cdn']media_loc = cdn_loc.replace('cdn', 'media-files')- if "12" in media_loc:- media_loc = media_loc.replace('.ru', '.la')referrer = "https://stream.bunkr.ru/v/" + file['name']link = URL(media_loc + '/' + file['name'])- elif ext in FILE_FORMATS['Other']:+ elif ext in FILE_FORMATS['Images']:+ link = URL(file['i'] + '/' + file['name'])+ referrer = url+ else:cdn_loc = file['cdn']media_loc = cdn_loc.replace('cdn', 'media-files')- if "12" in media_loc:- media_loc = media_loc.replace('.ru', '.la')referrer = "https://files.bunkr.ru/d/" + file['name']link = URL(media_loc + '/' + file['name'])- else:- link = URL(file['cdn'] + '/' + file['name'])- await domain_obj.add_to_album(title, link, referrer)-- except Exception as e:- logger.debug("Error encountered while handling %s", str(url), exc_info=True)- await log("Error scraping " + str(url), quiet=self.quiet)- logger.debug(e)-- await log("Finished scrape of " + str(url), quiet=self.quiet)- return domain_obj+ if "12" in link.host:+ link = link.with_host(url.host.replace('.ru', '.la').replace('.su', '.la'))- async def stream(self, session: Session, url: URL):- try:- await log("Starting scrape of " + str(url), quiet=self.quiet)- soup = await session.get_BS4(url)- json_obj = json.loads(soup.select_one("script[id=__NEXT_DATA__]").text)- if not json_obj['props']['pageProps']:- try:- 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 = {'props': json.loads(text)}- except:- raise Exception("Couldn't get link from HTML")- link = URL(json_obj['props']['pageProps']['file']['mediafiles'] + '/' + json_obj['props']['pageProps']['file']['name'])- return link+ completed = False+ if filename in completed_files:+ completed = True+ media = MediaItem(link, referrer, completed, filename, ext)+ await album.add_media(media)+ return albumexcept Exception as e:logger.debug("Error encountered while handling %s", str(url), exc_info=True)- await log("Error scraping " + str(url), quiet=self.quiet)+ await log(f"[red]Error: {str(url)}[/red]", quiet=self.quiet)logger.debug(e)+ return Nonediff --git a/cyberdrop_dl/crawlers/Coomer_Spider.py b/cyberdrop_dl/crawlers/Coomer_Spider.pydeleted file mode 100644index 3309e637a..000000000--- a/cyberdrop_dl/crawlers/Coomer_Spider.py+++ /dev/null@@ -1,113 +0,0 @@-import asyncio--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, scraping_mapper, separate_posts=False, quiet: bool):- self.include_id = include_id- self.quiet = quiet- self.scraping_mapper = scraping_mapper- self.separate_posts = separate_posts-- async def fetch(self, session: Session, url: URL):- await log("Starting scrape of " + str(url), quiet=self.quiet)- 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)- elif "post" in url.parts:- results = await self.parse_post(session, url, None)- for result in results:- await domain_obj.add_to_album(result[0], result[1], result[2])- 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), quiet=self.quiet)- 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 = []- posts += soup.select("h2[class=post-card__heading] a")- 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), quiet=self.quiet)- logger.debug(e)- return []-- async def parse_post(self, session: Session, url: URL, title=None):- try:- await log("Scraping post: " + str(url), quiet=self.quiet)- soup = await session.get_BS4(url)- results = []-- if self.separate_posts:- if self.include_id:- if title:- title = title + '/' + str(url.parts[-1]) + " - " + await make_title_safe(soup.select_one("h1[class=post__title]").text.replace('\n', '').replace("..", ""))- else:- title = await make_title_safe(str(url.parts[-1]) + " - " + soup.select_one("h1[class=post__title]").text.replace('\n', '').replace("..", ""))- else:- if title:- title = title + '/' + await make_title_safe(soup.select_one("h1[class=post__title]").text.replace('\n', '').replace("..", ""))- else:- title = await make_title_safe(soup.select_one("h1[class=post__title]").text.replace('\n', '').replace("..", ""))- else:- if not 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])-- text_content = soup.select("div[class=post__content] a")- tasks = []- for content in text_content:- link = URL(content.get('href'))- tasks.append(self.scraping_mapper.map_url(link, title))- await asyncio.gather(*tasks)-- return results-- except Exception as e:- logger.debug("Error encountered while handling %s", str(url), exc_info=True)- await log("Error scraping " + str(url), quiet=self.quiet)- logger.debug(e)- return []diff --git a/cyberdrop_dl/crawlers/Cyberdrop_Spider.py b/cyberdrop_dl/crawlers/Cyberdrop_Spider.pyindex 5168efe05..8fa3579ce 100644--- a/cyberdrop_dl/crawlers/Cyberdrop_Spider.py+++ b/cyberdrop_dl/crawlers/Cyberdrop_Spider.py@@ -1,26 +1,50 @@+from pathlib import Path+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+from ..base_functions.base_functions import log, logger, make_title_safe, check_direct, get_filename_and_ext+from ..base_functions.data_classes import AlbumItem, MediaItem+from ..base_functions.error_classes import NoExtensionFailure+from ..base_functions.sql_helper import SQLHelper+from ..client.client import ScrapeSessionclass CyberdropCrawler:- def __init__(self, *, include_id=False, quiet: bool):+ def __init__(self, *, include_id=False, quiet: bool, SQL_Helper: SQLHelper):self.include_id = include_id+ self.SQL_Helper = SQL_Helperself.quiet = quiet- async def fetch(self, session: Session, url: URL):- domain_obj = DomainItem(url.host, {})+ async def fetch(self, session: ScrapeSession, url: URL):+ album_obj = AlbumItem("Cyberdrop Loose Files", [])+ await log(f"[green]Starting: {str(url)}[/green]", quiet=self.quiet)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), quiet=self.quiet)+ complete = await self.SQL_Helper.check_complete_singular("cyberdrop", url.path)+ filename, ext = await get_filename_and_ext(url.name)+ media = MediaItem(url, url, complete, filename, ext)+ await album_obj.add_media(media)+ await self.SQL_Helper.insert_album("cyberdrop", "", album_obj)+ await log(f"[green]Finished: {str(url)}[/green]", quiet=self.quiet)+ return album_objtry:+ existing = await self.SQL_Helper.get_existing_album("bunkr", url.path)+ existing_files = []+ if existing:+ title = Path(existing[0][-4]).name+ await album_obj.set_new_title(title)+ all_complete = True+ for file in existing:+ if file[-1] == 1:+ existing_files.append(file[-2])+ media = MediaItem(url, url, True, file[-2], "." + file[-2].rsplit('.')[-1])+ await album_obj.add_media(media)+ else:+ all_complete = False+ if all_complete:+ return album_obj+soup = await session.get_BS4(url)title = soup.select_one("h1[id=title]").get_text()@@ -31,19 +55,27 @@ class CyberdropCrawler:titlep2 = [s for s in titlep2 if "." in s][-1]title = title + " - " + titlep2title = await make_title_safe(title.replace(r"\n", "").strip())+ await album_obj.set_new_title(title)links = soup.select('div[class="image-container column"] a')for link in links:link = URL(link.get('href'))- if 'cyberdrop' in link.host:- link = URL('https://fs-01.cyberdrop.cc').with_name(link.name)- await domain_obj.add_to_album(title, link, url)+ try:+ filename, ext = await get_filename_and_ext(link.name)+ except NoExtensionFailure:+ continue++ if filename in existing_files:+ continue+ media = MediaItem(link, url, False, filename, ext)+ await album_obj.add_media(media)except Exception as e:logger.debug("Error encountered while handling %s", str(url), exc_info=True)- await log("Error scraping " + str(url), quiet=self.quiet)+ await log(f"[red]Error: {str(url)}[/red]", quiet=self.quiet)logger.debug(e)+ return album_obj- await log("Finished scrape of " + str(url), quiet=self.quiet)-- return domain_obj+ await self.SQL_Helper.insert_album("cyberdrop", url.path, album_obj)+ await log(f"[green]Finished: {str(url)}[/green]", quiet=self.quiet)+ return album_objdiff --git a/cyberdrop_dl/crawlers/Cyberfile_Spider.py b/cyberdrop_dl/crawlers/Cyberfile_Spider.pydeleted file mode 100644index c160736e5..000000000--- a/cyberdrop_dl/crawlers/Cyberfile_Spider.py+++ /dev/null@@ -1,203 +0,0 @@-import re--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, quiet: bool):- self.quiet = quiet- self.load_files = URL('https://cyberfile.su/account/ajax/load_files')- self.file_details = URL('https://cyberfile.su/account/ajax/file_details')-- async def fetch(self, session: Session, url: URL):- await log("Starting scrape of " + str(url), quiet=self.quiet)- domain_obj = DomainItem("cyberfile.su", {})- 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), quiet=self.quiet)- 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), quiet=self.quiet)- 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), quiet=self.quiet)- 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.get_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), quiet=self.quiet)- 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("a[onclick*=loadImages]")[-1].get('onclick').split(',')[2])- 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), quiet=self.quiet)- logger.debug(e)- return []-- async def folder_content(self, session, url: URL, nodeId, page, title=None):- data = {"pageType": "folder", "nodeId": nodeId, "pageStart": page, "perPage": 0, "filterOrderBy": ""}- nodes = []- contents = []- try:- content = await session.post(self.load_files, data)- text = content['html']- if title:- title = title + "/" + content['page_title']- else:- title = content['page_title']- soup = BeautifulSoup(text.replace("\\", ""), 'html.parser')- total_pages = int(soup.select("a[onclick*=loadImages]")[-1].get('onclick').split(',')[2])- 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, title))- return contents-- except Exception as e:- await log("Error scraping " + str(url), quiet=self.quiet)- 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), quiet=self.quiet)- logger.debug(e)- return []diff --git a/cyberdrop_dl/crawlers/Erome_Spider.py b/cyberdrop_dl/crawlers/Erome_Spider.pydeleted file mode 100644index 5c6dfcbb8..000000000--- a/cyberdrop_dl/crawlers/Erome_Spider.py+++ /dev/null@@ -1,42 +0,0 @@-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, quiet: bool):- self.include_id = include_id- self.quiet = quiet-- async def fetch(self, session: Session, url: URL):- domain_obj = DomainItem(url.host, {})-- await log("Starting scrape of " + str(url), quiet=self.quiet)-- 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), quiet=self.quiet)- logger.debug(e)-- await log("Finished scrape of " + str(url), quiet=self.quiet)-- return domain_objdiff --git a/cyberdrop_dl/crawlers/Fapello_Spider.py b/cyberdrop_dl/crawlers/Fapello_Spider.pydeleted file mode 100644index 1f2c4c5f0..000000000--- a/cyberdrop_dl/crawlers/Fapello_Spider.py+++ /dev/null@@ -1,81 +0,0 @@-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 FapelloCrawler:- def __init__(self, *, include_id=False, quiet: bool):- self.include_id = include_id- self.quiet = quiet-- async def fetch(self, session: Session, url: URL):- await log("Starting scrape of " + str(url), quiet=self.quiet)- domain_obj = DomainItem('fapello', {})- results = []-- 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), quiet=self.quiet)- return domain_obj-- async def parse_profile(self, session: Session, url: URL):- try:- soup, returned_url = await session.get_BS4_and_url(url)- title = soup.select_one('h2[class="font-semibold lg:text-2xl text-lg mb-2 mt-4"]').get_text()- title = title + " (Fapello)"- results = []-- # Fapello does circular looped paging- if returned_url != url:- return results-- content_section = soup.select_one("div[id=content]")- posts = content_section.select("a")- for post in posts:- link = post.get('href')- if link:- results.extend(await self.parse_post(session, link, title))-- next_page = soup.select_one('div[id="next_page"] a')- if next_page:- next_page = next_page.get('href')- if next_page:- results.extend(await self.parse_profile(session, URL(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), quiet=self.quiet)- logger.debug(e)- return []-- async def parse_post(self, session: Session, url: URL, title=None):- try:- await log("Scraping post: " + str(url), quiet=self.quiet)- soup = await session.get_BS4(url)- results = []-- content_section = soup.select_one('div[class="flex justify-between items-center"]')-- images = content_section.select("img")- for image in images:- download_link = URL(image.get('src'))- results.append([title, download_link, url])-- videos = content_section.select("source")- for video in videos:- download_link = URL(video.get('src'))- 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), quiet=self.quiet)- logger.debug(e)- return []\ No newline at end of filediff --git a/cyberdrop_dl/crawlers/Gfycat_Spider.py b/cyberdrop_dl/crawlers/Gfycat_Spider.pydeleted file mode 100644index 9fb6ee585..000000000--- a/cyberdrop_dl/crawlers/Gfycat_Spider.py+++ /dev/null@@ -1,33 +0,0 @@-from yarl import URL--from ..base_functions.base_functions import log, logger-from ..client.client import Session---class GfycatCrawler:- def __init__(self, *, include_id=False, quiet: bool):- self.include_id = include_id- self.quiet = quiet-- 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), quiet=self.quiet)- logger.debug(e)diff --git a/cyberdrop_dl/crawlers/GoFile_Spider.py b/cyberdrop_dl/crawlers/GoFile_Spider.pydeleted file mode 100644index 83fd6a331..000000000--- a/cyberdrop_dl/crawlers/GoFile_Spider.py+++ /dev/null@@ -1,64 +0,0 @@-import http-from typing import Union--from gofile import Gofile-from yarl import URL--from ..base_functions.base_functions import log-from ..base_functions.data_classes import DomainItem-from ..client.client import Session---class GofileCrawler():- def __init__(self, quiet: bool):- self.quiet = quiet- self.client = Gofile()-- async def fetch(self, session: Session, url: URL):- domain_obj = DomainItem('gofile.io', {})-- # Set cookie in cookie_jar- client_token = self.client.token- morsel = http.cookies.Morsel()- morsel['domain'] = 'gofile.io'- morsel.set('accountToken', client_token, client_token)- session.client_session.cookie_jar.update_cookies({'gofile.io': morsel})-- results = await self.get_links(url)-- await log("Starting scrape of " + str(url), quiet=self.quiet)-- 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), quiet=self.quiet)-- return domain_obj-- async def get_links(self, url: URL, og_title=None):- results = []- content_id = url.name if url.host == 'gofile.io' else url- try:- content = self.client.get_content(content_id)- except:- await log("Error scraping " + str(url), quiet=self.quiet)- return- if not content:- return-- title = content["name"]- if og_title is not None:- title = og_title + '/' + title-- contents: dict[str, dict[str, Union[str, int]]] = content["contents"]- for val in contents.values():- if val["type"] == "folder":- try:- results.extend(result for result in await self.get_links(URL("https://gofile.io/d/"+val["code"]), title))- except Exception as e:- await log(f"Error scraping gofile: {val['code']}", quiet=self.quiet)- else:- results.append({'url': URL(val["link"]) if val["link"] != "overloaded" else URL(val["directLink"]),- 'title': title, 'referral': URL(url)})- return resultsdiff --git a/cyberdrop_dl/crawlers/HGameCG_Spider.py b/cyberdrop_dl/crawlers/HGameCG_Spider.pydeleted file mode 100644index 7fdbf2d7d..000000000--- a/cyberdrop_dl/crawlers/HGameCG_Spider.py+++ /dev/null@@ -1,58 +0,0 @@-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 HGameCGCrawler:- def __init__(self, *, include_id=False, quiet: bool):- self.include_id = include_id- self.quiet = quiet-- async def fetch(self, session: Session, url: URL):- domain_obj = DomainItem(url.host, {})-- await log("Starting scrape of " + str(url), quiet=self.quiet)- results = await self.get_album(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), quiet=self.quiet)- return domain_obj-- async def get_album(self, session: Session, url: URL):- results = []- try:- soup = await session.get_BS4(url)- title = await make_title_safe(soup.select_one("div[class=navbar] h1").get_text())- results = []-- images = soup.select("div[class=image] a")- for image in images:- image = image.get('href')- image = URL("https://" + url.host + image)- link = await self.get_image(session, image)- results.append({'url': link, 'title': title, 'referral': url, 'cookies': ''})-- next_page = soup.find("a", text="Next Page")- if next_page is not None:- next_page = next_page.get('href')- if next_page is not None:- next_page = URL("https://" + url.host + next_page)- results.extend(result for result in await self.get_album(session, next_page))-- except Exception as e:- logger.debug("Error encountered while handling %s", str(url), exc_info=True)- await log("Error scraping " + str(url), quiet=self.quiet)- logger.debug(e)-- return results-- async def get_image(self, session: Session, url: URL):- try:- soup = await session.get_BS4(url)- image = soup.select_one("div[class=hgamecgimage] img")- image = URL(image.get('src'))- return image- except:- logger.error(f"Unable to get image from {str(url)}")diff --git a/cyberdrop_dl/crawlers/ImgBox_Spider.py b/cyberdrop_dl/crawlers/ImgBox_Spider.pydeleted file mode 100644index 640d887b1..000000000--- a/cyberdrop_dl/crawlers/ImgBox_Spider.py+++ /dev/null@@ -1,54 +0,0 @@-from typing import Dict--from yarl import URL--from ..base_functions.base_functions import log, logger, check_direct-from ..base_functions.data_classes import DomainItem-from ..client.client import Session---class ImgBoxCrawler:- def __init__(self, *, include_id=False, quiet: bool):- self.include_id = include_id- self.quiet = quiet-- async def fetch(self, session: Session, url: URL):- domain_obj = DomainItem(url.host, {})- await log("Starting scrape of " + str(url), quiet=self.quiet)-- if await check_direct(url):- await domain_obj.add_to_album(link=URL(url), referral=url, title="ImgBox Loose Files")- return domain_obj-- try:- if "g" in url.parts:- images = await self.folder(session, url)- for img in images:- await domain_obj.add_to_album(url.raw_name, img, url)- else:- img = await self.singular(session, url)- await domain_obj.add_to_album("Loose ImgBox Files", img, url)-- except Exception as e:- logger.debug("Error encountered while handling %s", str(url), exc_info=True)- await log("Error scraping " + str(url), quiet=self.quiet)- logger.debug(e)-- await log("Finished scrape of " + str(url), quiet=self.quiet)-- return domain_obj-- async def folder(self, session: Session, url: URL):- soup = await session.get_BS4(url)- output = []-- images = soup.find('div', attrs={'id': 'gallery-view-content'})- for link in images.findAll("img"):- output.append(URL(link.get('src').replace("thumbs", "images").replace("_b", "_o")))-- return output-- async def singular(self, session: Session, url: URL):- soup = await session.get_BS4(url)- link = URL(soup.select_one("img[id=img]").get('src'))- return linkdiff --git a/cyberdrop_dl/crawlers/Kemono_Spider.py b/cyberdrop_dl/crawlers/Kemono_Spider.pydeleted file mode 100644index 800249b45..000000000--- a/cyberdrop_dl/crawlers/Kemono_Spider.py+++ /dev/null@@ -1,114 +0,0 @@-import asyncio--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, scraping_mapper, separate_posts=False, quiet: bool):- self.include_id = include_id- self.quiet = quiet- self.scraping_mapper = scraping_mapper- self.separate_posts = separate_posts-- async def fetch(self, session: Session, url: URL):- await log("Starting scrape of " + str(url), quiet=self.quiet)- 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)- elif "post" in url.parts:- results = await self.parse_post(session, url, None)- for result in results:- await domain_obj.add_to_album(result[0], result[1], result[2])- 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), quiet=self.quiet)- 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 = []- posts += soup.select('article[class="post-card post-card--preview"] a')- posts += soup.select('article[class="post-card"] a')- 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[class=next]')- 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), quiet=self.quiet)- logger.debug(e)- return []-- async def parse_post(self, session: Session, url: URL, title=None):- try:- await log("Scraping post: " + str(url), quiet=self.quiet)- soup = await session.get_BS4(url)- results = []-- if self.separate_posts:- if self.include_id:- if title:- title = title + '/' + str(url.parts[-1]) + " - " + await make_title_safe(soup.select_one("h1[class=post__title]").text.replace('\n', '').replace("..", ""))- else:- title = await make_title_safe(str(url.parts[-1]) + " - " + soup.select_one("h1[class=post__title]").text.replace('\n', '').replace("..", ""))- else:- if title:- title = title + '/' + await make_title_safe(soup.select_one("h1[class=post__title]").text.replace('\n', '').replace("..", ""))- else:- title = await make_title_safe(soup.select_one("h1[class=post__title]").text.replace('\n', '').replace("..", ""))- else:- if not 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])-- text_content = soup.select("div[class=post__content] a")- tasks = []- for content in text_content:- link = URL(content.get('href'))- tasks.append(self.scraping_mapper.map_url(link, title))- await asyncio.gather(*tasks)-- return results-- except Exception as e:- logger.debug("Error encountered while handling %s", str(url), exc_info=True)- await log("Error scraping " + str(url), quiet=self.quiet)- logger.debug(e)- return []diff --git a/cyberdrop_dl/crawlers/Pixeldrain_Spider.py b/cyberdrop_dl/crawlers/Pixeldrain_Spider.pydeleted file mode 100644index 253b3c08c..000000000--- a/cyberdrop_dl/crawlers/Pixeldrain_Spider.py+++ /dev/null@@ -1,44 +0,0 @@-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 PixelDrainCrawler:- def __init__(self, quiet: bool):- self.quiet = quiet- self.api = URL('https://pixeldrain.com/api/')-- async def fetch(self, session: Session, url: URL):- await log("Starting scrape of " + str(url), quiet=self.quiet)- domain_obj = DomainItem("pixeldrain.com", {})-- identifier = str(url).split('/')[-1]- if url.parts[1] == 'l':- links = await self.get_listings(session, identifier, url)- if links:- for link in links:- await domain_obj.add_to_album(identifier, link, url)- else:- 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), quiet=self.quiet)- 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), quiet=self.quiet)- 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/Postimg_Spider.py b/cyberdrop_dl/crawlers/Postimg_Spider.pydeleted file mode 100644index cb3436908..000000000--- a/cyberdrop_dl/crawlers/Postimg_Spider.py+++ /dev/null@@ -1,56 +0,0 @@-from typing import Dict--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 PostImgCrawler:- def __init__(self, *, include_id=False, quiet: bool):- self.include_id = include_id- self.quiet = quiet-- async def fetch(self, session: Session, url: URL):- domain_obj = DomainItem(url.host, {})- await log("Starting scrape of " + str(url), quiet=self.quiet)-- try:- if "gallery" in url.parts:- listed = await self.folder(session, url)- for referer, img in listed.items():- await domain_obj.add_to_album(url.raw_name, img, referer)- else:- img = await self.singular(session, url)- await domain_obj.add_to_album("Loose PostIMG Files", img, url)-- except Exception as e:- logger.debug("Error encountered while handling %s", str(url), exc_info=True)- await log("Error scraping " + str(url), quiet=self.quiet)- logger.debug(e)-- await log("Finished scrape of " + str(url), quiet=self.quiet)-- return domain_obj-- async def folder(self, session: Session, url: URL):- album = url.raw_name- data = {"action": "list", "album": album}- output = {}- i = 1- while True:- data_used = data- data_used["page"] = i- data_out = await session.post(URL("https://postimg.cc/json"), data_used)- if data_out['status_code'] != 200 or not data_out['images']:- break- for item in data_out['images']:- output[URL("https://postimg.cc/" + item[0])] = URL(item[4].replace(item[0], item[1]))- i += 1- return output-- async def singular(self, session: Session, url: URL):- soup = await session.get_BS4(url)- link = URL(soup.select_one("a[id=download]").get('href').replace("?dl=1", ""))- return linkdiff --git a/cyberdrop_dl/crawlers/Redgifs_Spider.py b/cyberdrop_dl/crawlers/Redgifs_Spider.pydeleted file mode 100644index 434c718a2..000000000--- a/cyberdrop_dl/crawlers/Redgifs_Spider.py+++ /dev/null@@ -1,33 +0,0 @@-from yarl import URL--from cyberdrop_dl.base_functions.base_functions import log, logger-from ..client.client import Session---class RedGifsCrawler:- def __init__(self, *, include_id=False, quiet: bool):- self.include_id = include_id- self.quiet = quiet-- 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), quiet=self.quiet)- logger.debug(e)diff --git a/cyberdrop_dl/crawlers/Rule34_Spider.py b/cyberdrop_dl/crawlers/Rule34_Spider.pydeleted file mode 100644index 552fcca66..000000000--- a/cyberdrop_dl/crawlers/Rule34_Spider.py+++ /dev/null@@ -1,40 +0,0 @@-from xml.etree.ElementTree import Element-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 Rule34Crawler:- def __init__(self, *, include_id=False, quiet: bool):- self.include_id = include_id- self.quiet = quiet-- async def fetch(self, session: Session, url: URL):- try:- # get the &id=1234 part from the url- # an url can look like this:- # https://rule34.xxx/index.php?page=post&s=view&id=6766683- id = url.query['id']-- # call the api for- # https://api.rule34.xxx/index.php?page=dapi&s=post&q=index&id=${OUR_ID}- apiUrl = URL("https://api.rule34.xxx/index.php?page=dapi&s=post&q=index&id=" + id)- response = await session.get_xml(apiUrl)-- for child in response:- if child.tag != "post":- continue- file_url = child.attrib["file_url"]- break-- domain_object = DomainItem("rule34.xxx", {})- await domain_object.add_to_album("Rule34", URL(file_url), url)-- return domain_object-- except Exception as e:- logger.debug("Error encountered while handling %s", str(url), exc_info=True)- await log("Error scraping " + str(url), quiet=self.quiet)- logger.debug(e)diff --git a/cyberdrop_dl/crawlers/Saint_Spider.py b/cyberdrop_dl/crawlers/Saint_Spider.pydeleted file mode 100644index bd6c0b13d..000000000--- a/cyberdrop_dl/crawlers/Saint_Spider.py+++ /dev/null@@ -1,29 +0,0 @@-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, quiet: bool):- self.include_id = include_id- self.quiet = quiet-- async def fetch(self, session: Session, url: URL):- domain_obj = DomainItem(url.host, {})- await log("Starting scrape of " + str(url), quiet=self.quiet)-- 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), quiet=self.quiet)- logger.debug(e)-- await log("Finished scrape of " + str(url), quiet=self.quiet)-- return domain_objdiff --git a/cyberdrop_dl/crawlers/ShareX_Spider.py b/cyberdrop_dl/crawlers/ShareX_Spider.pydeleted file mode 100644index d9b96d2a9..000000000--- a/cyberdrop_dl/crawlers/ShareX_Spider.py+++ /dev/null@@ -1,168 +0,0 @@-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, quiet: bool):- self.include_id = include_id- self.quiet = quiet-- async def fetch(self, session: Session, url: URL):- domain_obj = DomainItem(url.host, {})-- await log("Starting scrape of " + str(url), quiet=self.quiet)-- 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), quiet=self.quiet)-- 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))-- next_page = soup.select_one('li.pagination-next a')- if not next_page:- next_page = soup.select_one('a[data-pagination=next]')- 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_albums(session, next_page))-- except Exception as e:- logger.debug("Error encountered while handling %s", str(url), exc_info=True)- await log("Error scraping " + str(url), quiet=self.quiet)- 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), quiet=self.quiet)- 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), quiet=self.quiet)- 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())- results.extend(result for result in await self.get_list_links(session, url, title))-- except Exception as e:- logger.debug("Error encountered while handling %s", str(url), exc_info=True)- await log("Error scraping " + str(url), quiet=self.quiet)- 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 not next_page:- next_page = soup.select_one('a[data-pagination=next]')- 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), quiet=self.quiet)- logger.debug(e)- return results-- async def parse(self, session: Session, url: URL, og_title=None, page=None, prior_result=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-- try:- 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))- finally:- 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), quiet=self.quiet)- logger.debug(e)- return resultsdiff --git a/cyberdrop_dl/crawlers/SimpCity_Spider.py b/cyberdrop_dl/crawlers/SimpCity_Spider.pydeleted file mode 100644index 328d9cf21..000000000--- a/cyberdrop_dl/crawlers/SimpCity_Spider.py+++ /dev/null@@ -1,220 +0,0 @@-import asyncio-import re--from bs4 import BeautifulSoup-from yarl import URL--from ..base_functions.base_functions import log, logger, make_title_safe, write_last_post_file-from ..base_functions.data_classes import AuthData, CascadeItem-from ..client.client import Session---class SimpCityCrawler:- def __init__(self, *, include_id=False, auth: AuthData = None, scraping_mapper, separate_posts=False,- output_last=[False, None], quiet: bool):- self.include_id = include_id- self.quiet = quiet- self.separate_posts = separate_posts- self.output_last = output_last- 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), quiet=self.quiet)- 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 --simpcity-username and --simpcity-password", quiet=self.quiet)- await log("Not being logged in might cause issues.", quiet=self.quiet)- await self.parse_thread(session, url, cascade, "")- except Exception as e:- self.lock = 0- await log(f"there was an error signing into {url.host}", quiet=self.quiet)- await log(e, quiet=self.quiet)- return-- await log("Finished scrape of " + str(url), quiet=self.quiet)- 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- title = await make_title_safe(title.replace("\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])-- embed_url = re.search(r"https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\/[-a-zA-Z0-9@:%._\+~#=]*\/[-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.replace(".st", ".su") 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)- else:- if self.output_last[0]:- if 'page-' in url.raw_name:- last_post_url = url.parent / post_num_str- elif 'post-' in url.raw_name:- last_post_url = url.parent / post_num_str- else:- last_post_url = url / post_num_str- await write_last_post_file(self.output_last[1], str(last_post_url))-- return-- except Exception as e:- logger.debug("Error encountered while handling %s", str(url), exc_info=True)- await log("Error scraping " + str(url), quiet=self.quiet)- logger.debug(e)diff --git a/cyberdrop_dl/crawlers/SocialMediaGirls_Spider.py b/cyberdrop_dl/crawlers/SocialMediaGirls_Spider.pydeleted file mode 100644index 32b475b33..000000000--- a/cyberdrop_dl/crawlers/SocialMediaGirls_Spider.py+++ /dev/null@@ -1,220 +0,0 @@-import asyncio-import re--from bs4 import BeautifulSoup-from yarl import URL--from ..base_functions.base_functions import log, logger, make_title_safe, write_last_post_file-from ..base_functions.data_classes import AuthData, CascadeItem-from ..client.client import Session---class SocialMediaGirlsCrawler:- def __init__(self, *, include_id=False, auth: AuthData = None, scraping_mapper, separate_posts=False,- output_last=[False, None], quiet: bool):- self.include_id = include_id- self.quiet = quiet- self.separate_posts = separate_posts- self.output_last = output_last- 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), quiet=self.quiet)- 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 --socialmediagirls-username and --socialmediagirls-password", quiet=self.quiet)- await log("Not being logged in might cause issues.", quiet=self.quiet)- await self.parse_thread(session, url, cascade, "")- except Exception as e:- self.lock = 0- await log(f"there was an error signing into {url.host}", quiet=self.quiet)- await log(e, quiet=self.quiet)- return-- await log("Finished scrape of " + str(url), quiet=self.quiet)- return cascade-- async def parse_thread(self, session: Session, url: URL, cascade: CascadeItem, title: str):- try:- soup, url_return = await session.get_BS4_and_url(url)-- domain = URL("https://" + url.host)-- title_block = soup.select_one("h1[class=p-title-value]")- for elem in title_block.find_all("span"):- elem.decompose()-- if title:- pass- else:- title = title_block.text- title = await make_title_safe(title.replace("\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]- in_prog_title = temp_title + "/Attachments"- if 'smgmedia' in link.host:- await cascade.add_to_album(url.host, in_prog_title, link, url)- else:- 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)- else:- if self.output_last[0]:- if 'page-' in url.raw_name:- last_post_url = url.parent / post_num_str- elif 'post-' in url.raw_name:- last_post_url = url.parent / post_num_str- else:- last_post_url = url / post_num_str- await write_last_post_file(self.output_last[1], str(last_post_url))-- return-- except Exception as e:- logger.debug("Error encountered while handling %s", str(url), exc_info=True)- await log("Error scraping " + str(url), quiet=self.quiet)- logger.debug(e)diff --git a/cyberdrop_dl/crawlers/XBunker_Spider.py b/cyberdrop_dl/crawlers/XBunker_Spider.pydeleted file mode 100644index f6988e33e..000000000--- a/cyberdrop_dl/crawlers/XBunker_Spider.py+++ /dev/null@@ -1,216 +0,0 @@-import asyncio-import re--from bs4 import BeautifulSoup-from yarl import URL--from ..base_functions.base_functions import log, logger, make_title_safe, write_last_post_file-from ..base_functions.data_classes import AuthData, CascadeItem-from ..client.client import Session---class XBunkerCrawler:- def __init__(self, *, include_id=False, auth: AuthData = None, scraping_mapper, separate_posts=False,- output_last=[False, None], quiet: bool):- self.include_id = include_id- self.quiet = quiet- self.separate_posts = separate_posts- self.output_last = output_last- 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), quiet=self.quiet)- 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 --xbunker-username and --xbunker-password", quiet=self.quiet)- await log("Not being logged in might cause issues.", quiet=self.quiet)- await self.parse_thread(session, url, cascade, "")- except Exception as e:- self.lock = 0- await log(f"there was an error signing into {url.host}", quiet=self.quiet)- await log(e, quiet=self.quiet)- return-- await log("Finished scrape of " + str(url), quiet=self.quiet)- 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- title = await make_title_safe(title.replace("\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 url.host in x[0].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)- elif '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)- else:- if self.output_last[0]:- if 'page-' in url.raw_name:- last_post_url = url.parent / post_num_str- elif 'post-' in url.raw_name:- last_post_url = url.parent / post_num_str- else:- last_post_url = url / post_num_str- await write_last_post_file(self.output_last[1], str(last_post_url))-- return-- except Exception as e:- logger.debug("Error encountered while handling %s", str(url), exc_info=True)- await log("Error scraping " + str(url), quiet=self.quiet)- logger.debug(e)diff --git a/cyberdrop_dl/crawlers/XBunkr_Spider.py b/cyberdrop_dl/crawlers/XBunkr_Spider.pydeleted file mode 100644index ca918a524..000000000--- a/cyberdrop_dl/crawlers/XBunkr_Spider.py+++ /dev/null@@ -1,36 +0,0 @@-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 XBunkrCrawler:- def __init__(self, *, include_id=False, quiet: bool):- self.include_id = include_id- self.quiet = quiet-- async def fetch(self, session: Session, url: URL):- domain_obj = DomainItem(url.host, {})-- if "media" in url.host:- await domain_obj.add_to_album("Loose XBunkr Files", url, url)- return domain_obj-- try:- soup = await session.get_BS4(url)- links = soup.select("a[class=image]")- title = await make_title_safe(soup.select_one("h1[id=title]").text)- title = title.strip()- 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), quiet=self.quiet)- logger.debug(e)-- await log("Finished scrape of " + str(url), quiet=self.quiet)-- return domain_objdiff --git a/cyberdrop_dl/crawlers/Xenforo_Spider.py b/cyberdrop_dl/crawlers/Xenforo_Spider.pynew file mode 100644index 000000000..fd10feea2--- /dev/null+++ b/cyberdrop_dl/crawlers/Xenforo_Spider.py@@ -0,0 +1,453 @@+from __future__ import annotations++import asyncio+import re++from bs4 import BeautifulSoup+from yarl import URL++from ..base_functions.base_functions import log, make_title_safe, write_last_post_file, get_filename_and_ext, logger+from ..base_functions.data_classes import CascadeItem, MediaItem+from ..base_functions.error_classes import FailedLoginFailure, NoExtensionFailure+from ..base_functions.sql_helper import SQLHelper+from ..client.client import ScrapeSession+++class XenforoCrawler:+ def __init__(self, *, scraping_mapper, args: dict, SQL_Helper: SQLHelper, quiet: bool):+ self.include_id = args["Runtime"]["include_id"]+ self.quiet = quiet+ self.separate_posts = args["Forum_Options"]["separate_posts"]+ self.output_last = args["Forum_Options"]["output_last_forum_post"]+ self.output_last_file = args["Files"]["output_last_forum_post_file"]++ self.simpcity_logged_in = False+ self.simpcity_lock = False+ self.simpcity_username = args["Authentication"]["simpcity_username"]+ self.simpcity_password = args["Authentication"]["simpcity_password"]++ self.socialmediagirls_logged_in = False+ self.socialmediagirls_lock = False+ self.socialmediagirls_username = args["Authentication"]["socialmediagirls_username"]+ self.socialmediagirls_password = args["Authentication"]["socialmediagirls_password"]++ self.xbunker_logged_in = False+ self.xbunker_lock = False+ self.xbunker_username = args["Authentication"]["xbunker_username"]+ self.xbunker_password = args["Authentication"]["xbunker_password"]++ self.scraping_mapper = scraping_mapper+ self.SQL_Helper = SQL_Helper++ async def fetch(self, session: ScrapeSession, url: URL):+ await log(f"[green]Starting: {str(url)}[/green]", quiet=self.quiet)+ cascade = CascadeItem({})++ scrape_url, post_num = await self.get_thread_url_and_post_num(url)++ try:+ if "simpcity" in url.host:+ await self.simpcity_login(session, url)+ title = await self.parse_simpcity(session, scrape_url, cascade, "", post_num)+ if "socialmediagirls" in url.host:+ await self.socialmediagirls_login(session, url)+ title = await self.parse_socialmediagirls(session, scrape_url, cascade, "", post_num)+ if "xbunker" in url.host:+ await self.xbunker_login(session, url)+ title = await self.parse_xbunker(session, scrape_url, cascade, "", post_num)++ except Exception as e:+ logger.debug("Error encountered while handling %s", str(url), exc_info=True)+ await log(f"[red]Error: {str(url)}[/red]", quiet=self.quiet)+ logger.debug(e)+ return cascade, ""++ await self.SQL_Helper.insert_cascade(cascade)+ await log(f"[green]Finished: {str(url)}[/green]", quiet=self.quiet)+ return cascade, title++ async def simpcity_login(self, session: ScrapeSession, url: URL):+ if self.simpcity_username and self.simpcity_username:+ if not self.simpcity_lock:+ while True:+ if self.simpcity_logged_in:+ return+ self.simpcity_lock = True+ domain = URL("https://" + url.host) / "login"+ text = await session.get_text(domain)+ 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.simpcity_username, "password": self.simpcity_password,+ "_xfRedirect": str(domain)})+ await session.post_data_no_resp(domain / "login", data=data)+ text = await session.get_text(domain)+ if "You are already logged in" in text:+ self.simpcity_logged_in = True+ self.simpcity_lock = False+ return+ else:+ self.simpcity_lock = False+ raise FailedLoginFailure()+ else:+ await log("[red]Login wasn't provided for SimpCity[/red]", quiet=self.quiet)+ raise FailedLoginFailure()++ async def socialmediagirls_login(self, session: ScrapeSession, url: URL):+ if self.socialmediagirls_username and self.socialmediagirls_username:+ if self.socialmediagirls_lock:+ while True:+ if self.socialmediagirls_logged_in:+ return+ self.simpcity_lock = True+ domain = URL("https://" + url.host) / "login"+ text = await session.get_text(domain)+ 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.socialmediagirls_username, "password": self.socialmediagirls_password,+ "_xfRedirect": str(domain)})+ await session.post_data_no_resp(domain / "login", data=data)+ text = await session.get_text(domain)+ if "You are already logged in" in text:+ self.socialmediagirls_logged_in = True+ self.socialmediagirls_lock = False+ return+ else:+ self.socialmediagirls_lock = False+ raise FailedLoginFailure()+ else:+ await log("[red]Login wasn't provided for SocialMediaGirls[/red]", quiet=self.quiet)+ raise FailedLoginFailure()++ async def xbunker_login(self, session: ScrapeSession, url: URL):+ if self.xbunker_username and self.xbunker_password:+ if self.xbunker_lock:+ while True:+ if self.xbunker_logged_in:+ return+ self.xbunker_lock = True+ domain = URL("https://" + url.host) / "login"+ text = await session.get_text(domain)+ 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.xbunker_username, "password": self.xbunker_password,+ "_xfRedirect": str(domain)})+ await session.post_data_no_resp(domain / "login", data=data)+ text = await session.get_text(domain)+ if "You are already logged in" in text:+ self.xbunker_logged_in = True+ self.xbunker_lock = False+ return+ else:+ self.xbunker_lock = False+ raise FailedLoginFailure()+ else:+ await log("[red]Login wasn't provided for SocialMediaGirls[/red]", quiet=self.quiet)+ raise FailedLoginFailure()++ async def get_thread_url_and_post_num(self, url: URL):+ post_number = 0+ if "post-" in str(url):+ post_number_parts = str(url).rsplit("post-", 1)+ post_number = int(post_number_parts[-1].strip("/")) if len(post_number_parts) == 2 else 0+ url = URL(post_number_parts[0].rstrip("#"))+ return url, post_number++ async def get_links(self, post_content, selector, attribute, domain, temp_title):+ found_links = []+ links = post_content.select(selector)+ for link in links:+ link = link.get(attribute)+ if link.endswith("/"):+ link = link[:-1]+ if link.startswith('//'):+ link = "https:" + link+ elif link.startswith('/'):+ link = domain / link[1:]+ found_links.append([URL(link), temp_title])+ return found_links++ async def get_embedded(self, post_content, selector, attribute, domain, temp_title):+ found_links = []+ links = post_content.select(selector)+ for link in links:+ embed_data = link.get(attribute)+ 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.", ""))+ found_links.append([embed_url, temp_title])++ embed_url = re.search(r"https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\/[-a-zA-Z0-9@:%._\+~#=]*\/[-a-zA-Z0-9@:?&%._\+~#=]*", embed_data)+ if embed_url:+ embed_url = URL(embed_url.group(0).replace("www.", ""))+ found_links.append([embed_url, temp_title])+ return found_links++ async def filter_content_links(self, cascade: CascadeItem, content_links: list, url: URL, domain: str):+ forum_direct_urls = [x for x in content_links if x[0].host.replace(".st", ".su") 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 or 'content' in link.parts or 'data' in link.parts:+ completed = await self.SQL_Helper.check_complete_singular(domain, link.path)+ try:+ filename, ext = await get_filename_and_ext(link.name)+ except NoExtensionFailure:+ continue+ media = MediaItem(link, url, completed, filename, ext)+ await cascade.add_to_album(domain, in_prog_title, media)+ return content_links++ async def handle_external_links(self, content_links: list):+ 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)++ async def parse_simpcity(self, session: ScrapeSession, url: URL, cascade: CascadeItem, title: str,+ post_number: int):+ soup = await session.get_BS4(url)++ domain = URL("https://" + url.host)+ post_num_str = None+ content_links = []++ 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+ title = await make_title_safe(title.replace("\n", "").strip())++ 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]")++ # Get Links+ content_links.extend(await self.get_links(post_content, "a", "href", domain, temp_title))++ # Get Images+ content_links.extend(await self.get_links(post_content, "div[class='bbImageWrapper js-lbImage']", "data-src", domain, temp_title))+ content_links.extend(await self.get_links(post_content, "div[class='bbImageWrapper lazyload js-lbImage']", "data-src", domain, temp_title))++ # Get Videos:+ content_links.extend(await self.get_links(post_content, "video source", "src", domain, temp_title))+ content_links.extend(await self.get_links(post_content, "iframe[class=saint-iframe]", "src", domain, temp_title))++ # Get Other Embedded Content+ content_links.extend(await self.get_embedded(post_content, "span[data-s9e-mediaembed-iframe]", "data-s9e-mediaembed-iframe", domain, temp_title))++ # Get Attachments+ attachments_block = post.select_one("section[class=message-attachments]")+ content_links.extend(await self.get_links(post_content, "a[class='file-preview js-lbImage']", "href", domain, temp_title))++ # Handle links+ content_links = await self.filter_content_links(cascade, content_links, url, "simpcity")+ await self.handle_external_links(content_links)++ 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)+ await self.parse_simpcity(session, next_page, cascade, title, post_number)+ else:+ if self.output_last:+ if 'page-' in url.raw_name:+ last_post_url = url.parent / post_num_str+ elif 'post-' in url.raw_name:+ last_post_url = url.parent / post_num_str+ else:+ last_post_url = url / post_num_str+ await write_last_post_file(self.output_last_file, str(last_post_url))+ return title++ async def parse_socialmediagirls(self, session: ScrapeSession, url: URL, cascade: CascadeItem, title: str,+ post_number: int):+ soup = await session.get_BS4(url)++ domain = URL("https://" + url.host)+ post_num_str = None+ content_links = []++ 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+ title = await make_title_safe(title.replace("\n", "").strip())++ 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]")++ # Get Links+ content_links.extend(await self.get_links(post_content, "a", "href", domain, temp_title))++ # Get Images+ content_links.extend(await self.get_links(post_content, "div[class='bbImageWrapper js-lbImage']", "data-src", domain, temp_title))+ content_links.extend(await self.get_links(post_content, "div[class='bbImageWrapper lazyload js-lbImage']", "data-src", domain, temp_title))++ # Get Videos:+ content_links.extend(await self.get_links(post_content, "video source", "src", domain, temp_title))+ content_links.extend(await self.get_links(post_content, "iframe[class=saint-iframe]", "src", domain, temp_title))++ # Get Other Embedded Content+ content_links.extend(await self.get_embedded(post_content, "span[data-s9e-mediaembed-iframe]", "data-s9e-mediaembed-iframe", domain, temp_title))++ # Get Attachments+ attachments_block = post.select_one("section[class=message-attachments]")+ content_links.extend(await self.get_links(post_content, "a[class='file-preview js-lbImage']", "href", domain, temp_title))++ # Handle links+ content_links = await self.filter_content_links(cascade, content_links, url, "socialmediagirls")+ await self.handle_external_links(content_links)++ 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)+ await self.parse_socialmediagirls(session, next_page, cascade, title, post_number)+ else:+ if self.output_last:+ if 'page-' in url.raw_name:+ last_post_url = url.parent / post_num_str+ elif 'post-' in url.raw_name:+ last_post_url = url.parent / post_num_str+ else:+ last_post_url = url / post_num_str+ await write_last_post_file(self.output_last_file, str(last_post_url))+ return title++ async def parse_xbunker(self, session: ScrapeSession, url: URL, cascade: CascadeItem, title: str,+ post_number: int):+ soup = await session.get_BS4(url)++ domain = URL("https://" + url.host)+ post_num_str = None+ content_links = []++ 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+ title = await make_title_safe(title.replace("\n", "").strip())++ 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]")++ # Get Links+ content_links.extend(await self.get_links(post_content, "a", "href", domain, temp_title))++ # Get Images+ content_links.extend(await self.get_links(post_content, "div[class='bbImageWrapper js-lbImage']", "data-src", domain, temp_title))+ content_links.extend(await self.get_links(post_content, "div[class='bbImageWrapper lazyload js-lbImage']", "data-src", domain, temp_title))++ # Get Videos:+ content_links.extend(await self.get_links(post_content, "video source", "src", domain, temp_title))+ content_links.extend(await self.get_links(post_content, "iframe[class=saint-iframe]", "src", domain, temp_title))++ # Get Other Embedded Content+ content_links.extend(await self.get_embedded(post_content, "span[data-s9e-mediaembed-iframe]", "data-s9e-mediaembed-iframe", domain, temp_title))++ # Get Attachments+ attachments_block = post.select_one("section[class=message-attachments]")+ content_links.extend(await self.get_links(post_content, "a[class='file-preview js-lbImage']", "href", domain, temp_title))++ # Handle links+ content_links = await self.filter_content_links(cascade, content_links, url, "xbunker")+ await self.handle_external_links(content_links)++ 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)+ await self.parse_xbunker(session, next_page, cascade, title, post_number)+ else:+ if self.output_last:+ if 'page-' in url.raw_name:+ last_post_url = url.parent / post_num_str+ elif 'post-' in url.raw_name:+ last_post_url = url.parent / post_num_str+ else:+ last_post_url = url / post_num_str+ await write_last_post_file(self.output_last_file, str(last_post_url))+ return titlediff --git a/cyberdrop_dl/main.py b/cyberdrop_dl/main.pyindex c7750b79c..0bc075980 100644--- a/cyberdrop_dl/main.py+++ b/cyberdrop_dl/main.py@@ -1,207 +1,186 @@import argparse-import multiprocessing-from argparse import Namespaceimport asyncioimport loggingfrom pathlib import Path-from functools import wraps-from typing import Dict-from colorama import Fore+import richfrom yarl import URL-from cyberdrop_dl.scraper.scraper_helper import ScrapeMapper-from . import __version__ as VERSION-from cyberdrop_dl.base_functions.base_functions import clear, create_config, log, logger, purge_dir, regex_links, \- run_args, check_free_space-from cyberdrop_dl.base_functions.data_classes import AuthData, SkipData+from cyberdrop_dl.base_functions.base_functions import log, clear, regex_links, check_free_space, purge_dir+from cyberdrop_dl.base_functions.config_manager import run_args, document_argsfrom cyberdrop_dl.base_functions.sql_helper import SQLHelperfrom cyberdrop_dl.client.client import Client-from cyberdrop_dl.client.downloaders import get_downloaders-from cyberdrop_dl.scraper.scraper import scrape+from cyberdrop_dl.client.downloaders import download_cascade, download_forums+from cyberdrop_dl.scraper.Scraper import ScrapeMapper+from . import __version__ as VERSION+from .base_functions.data_classes import SkipData, CascadeItem, ForumItem-def parse_args():+def parse_args() -> argparse.Namespace:+ """Parses the command line arguments passed into the program"""parser = argparse.ArgumentParser(description="Bulk downloader for multiple file hosts")parser.add_argument("-V", "--version", action="version", version="%(prog)s " + VERSION)++ # Path optionsparser.add_argument("-i", "--input-file", type=Path, help="file containing links to download", default="URLs.txt")parser.add_argument("-o", "--output-folder", type=Path, help="folder to download files to", default="Downloads")- parser.add_argument("--log-file", type=Path, help="log file to write to", default="downloader.log")+parser.add_argument("--config-file", type=Path, help="config file to read arguments from", default="config.yaml")parser.add_argument("--db-file", type=Path, help="history database file to write to", default="download_history.sqlite")- parser.add_argument("--threads", type=int, help="number of threads to use (0 = max)", default=0)+ parser.add_argument("--output-last-forum-file", type=Path, help="the text file to output last scraped post from a forum thread for re-feeding into CDL", default="URLs_Last_Post.txt")+ parser.add_argument("--unsupported-urls-file", type=Path, help="the csv file to output unsupported links into", default="Unsupported_URLs.csv")+ parser.add_argument("--log-file", type=Path, help="log file to write to", default="downloader.log")++ # Ignore+ parser.add_argument("--exclude-audio", help="skip downloading of audio files", action="store_true")+ parser.add_argument("--exclude-images", help="skip downloading of image files", action="store_true")+ parser.add_argument("--exclude-other", help="skip downloading of images", action="store_true")+ parser.add_argument("--exclude-videos", help="skip downloading of video files", action="store_true")+ parser.add_argument("--ignore-cache", help="this ignores previous runs cached scrape history", action="store_true")+ parser.add_argument("--ignore-history", help="this ignores previous download history", action="store_true")+ parser.add_argument("--skip", dest="skip_hosts", choices=SkipData.supported_hosts, help="This removes host links from downloads", action="append", default=[])++ # Runtime arguments+ parser.add_argument("--allow-insecure-connections", help="Allows insecure connections from content hosts", action="store_true")parser.add_argument("--attempts", type=int, help="number of attempts to download each file", default=10)- parser.add_argument("--connection-timeout", type=int, help="number of seconds to wait attempting to connect to a URL during the downloading phase", default=15)parser.add_argument("--disable-attempt-limit", help="disables the attempt limitation", action="store_true")parser.add_argument("--include-id", help="include the ID in the download folder name", action="store_true")- parser.add_argument("--exclude-videos", help="skip downloading of video files", action="store_true")- parser.add_argument("--exclude-images", help="skip downloading of image files", action="store_true")- parser.add_argument("--exclude-audio", help="skip downloading of audio files", action="store_true")- parser.add_argument("--exclude-other", help="skip downloading of images", action="store_true")- parser.add_argument("--ignore-history", help="This ignores previous download history", action="store_true")- parser.add_argument("--output-last-forum-post", help="Outputs the last post of a forum scrape to use as a starting point for future runs", action="store_true")+ parser.add_argument("--mark-downloaded", help="sets the scraped files as downloaded without downloading", action="store_true")parser.add_argument("--proxy", help="HTTP/HTTPS proxy used for downloading, format [protocal]://[ip]:[port]", default=None)- parser.add_argument("--separate-posts", help="Separates forum scraping into folders by post number", action="store_true")- parser.add_argument("--mark-downloaded", help="Sets the scraped files as downloaded without downloading", action="store_true")- parser.add_argument("--required-free-space", type=int, help="Required free space (in gigabytes) for the program to run", default=5)+ parser.add_argument("--required-free-space", type=int, help="required free space (in gigabytes) for the program to run", default=5)+ parser.add_argument("--simultaneous-downloads", type=int, help="number of threads to use (0 = max)", default=0)++ # Ratelimiting+ parser.add_argument("--connection-timeout", type=int, help="number of seconds to wait attempting to connect to a URL during the downloading phase", default=15)+ 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)++ # Forum Options+ parser.add_argument("--output-last-forum-post", help="outputs the last post of a forum scrape to use as a starting point for future runs", action="store_true")+ parser.add_argument("--separate-posts", help="separates forum scraping into folders by post number", action="store_true")++ # Authentication detailsparser.add_argument("--pixeldrain-api-key", type=str, help="api key for premium pixeldrain", default=None)- parser.add_argument("--xbunker-username", type=str, help="username to login to xbunker", default=None)- parser.add_argument("--xbunker-password", type=str, help="password to login to xbunker", default=None)- parser.add_argument("--socialmediagirls-username", type=str, help="username to login to socialmediagirls", default=None)- parser.add_argument("--socialmediagirls-password", type=str, help="password to login to socialmediagirls", default=None)- parser.add_argument("--simpcity-username", type=str, help="username to login to simpcity", default=None)parser.add_argument("--simpcity-password", type=str, help="password to login to simpcity", default=None)- parser.add_argument("--jdownloader-enable", help="enables sending unsupported URLs to a running jdownloader2 instance to download", action="store_true")+ parser.add_argument("--simpcity-username", type=str, help="username to login to simpcity", default=None)+ parser.add_argument("--socialmediagirls-password", type=str, help="password to login to socialmediagirls", default=None)+ parser.add_argument("--socialmediagirls-username", type=str, help="username to login to socialmediagirls", default=None)+ parser.add_argument("--xbunker-password", type=str, help="password to login to xbunker", default=None)+ parser.add_argument("--xbunker-username", type=str, help="username to login to xbunker", default=None)++ # JDownloader details+ parser.add_argument("--apply_jdownloader", help="enables sending unsupported URLs to a running jdownloader2 instance to download", action="store_true")parser.add_argument("--jdownloader-username", type=str, help="username to login to jdownloader", default=None)parser.add_argument("--jdownloader-password", type=str, help="password to login to jdownloader", default=None)parser.add_argument("--jdownloader-device", type=str, help="device name to login to for jdownloader", 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)++ # Linksparser.add_argument("links", metavar="link", nargs="*", help="link to content to download (passing multiple links is supported)", default=[])args = parser.parse_args()return args-async def handle_args(args: argparse.Namespace):- print_args = Namespace(**vars(args)).__dict__- print_args['xbunker_password'] = '!REDACTED!'- print_args['socialmediagirls_password'] = '!REDACTED!'- print_args['simpcity_password'] = '!REDACTED!'- print_args['jdownloader_password'] = '!REDACTED!'-- logging.debug("Creating Config")- cmd_args = Namespace(**vars(args)).__dict__- await create_config(args.config_file, print_args)-- await log("Getting Run Args")- use_args = await run_args(args.config_file, cmd_args)-- auth_args = use_args['Authentication']- auth_args_print = auth_args.copy()- auth_args_print['xbunker_password'] = '!REDACTED!'- auth_args_print['socialmediagirls_password'] = '!REDACTED!'- auth_args_print['simpcity_password'] = '!REDACTED!'- auth_args_print['pixeldrain_api_key'] = '!REDACTED!'-- file_args = use_args['Files']- for key, value in file_args.items():- file_args[key] = Path(value)-- jdownloader_args = use_args['JDownloader']- jdownloader_args_print = jdownloader_args.copy()- jdownloader_args_print['jdownloader_password'] = '!REDACTED!'-- runtime_args = use_args['Runtime']-- logging.debug(f"Starting Cyberdrop-DL")- logging.debug(f"Using authorization arguments: {auth_args_print}")- logging.debug(f"Using file arguments: {file_args}")- logging.debug(f"Using jdownloader arguments: {jdownloader_args_print}")- logging.debug(f"Using runtime arguments: {runtime_args}")-- return auth_args, file_args, jdownloader_args, runtime_args---async def download_all(auth_args: Dict, file_args: Dict, jdownloader_args: Dict, runtime_args: Dict, links: list,- client: Client, SQL_helper: SQLHelper, threads: int):- xbunker_auth = AuthData(auth_args['xbunker_username'], auth_args['xbunker_password'])- socialmediagirls_auth = AuthData(auth_args['socialmediagirls_username'], auth_args['socialmediagirls_password'])- simpcity_auth = AuthData(auth_args['simpcity_username'], auth_args['simpcity_password'])- jdownloader_auth = AuthData(jdownloader_args['jdownloader_username'], jdownloader_args['jdownloader_password'])- pixeldrain_api_key = auth_args['pixeldrain_api_key']-- skip_data = SkipData(runtime_args['skip_hosts'])- excludes = {'videos': runtime_args['exclude_videos'], 'images': runtime_args['exclude_images'],- 'audio': runtime_args['exclude_audio'], 'other': runtime_args['exclude_other']}-- if not await check_free_space(runtime_args['required_free_space'], file_args['output_folder']):- await log("Not enough free space to run the program.", Fore.RED)- return-- content_object = await scrape(urls=links, client=client, file_args=file_args, jdownloader_args=jdownloader_args,- runtime_args=runtime_args, jdownloader_auth=jdownloader_auth, simpcity_auth=simpcity_auth,- socialmediagirls_auth=socialmediagirls_auth, xbunker_auth=xbunker_auth,- skip_data=skip_data, quiet=False)-- if await content_object.is_empty():- logging.error('ValueError No links')- await log("No links found during scraping, check passwords or that the urls are accessible", Fore.RED)- await log("This program does not currently support password protected albums.", Fore.RED)- exit(0)- await clear()+async def file_management(args: dict, links: list) -> None:+ """We handle file defaults here (resetting and creation)"""+ input_file = args['Files']['input_file']+ if not input_file.is_file() and not links:+ input_file.touch()- backup_scraper = ScrapeMapper(client=client, file_args=file_args, jdownloader_args=jdownloader_args,- runtime_args=runtime_args, jdownloader_auth=jdownloader_auth,- simpcity_auth=simpcity_auth, socialmediagirls_auth=socialmediagirls_auth,- xbunker_auth=xbunker_auth, skip_data=skip_data, quiet=True)+ if args['Forum_Options']['output_last_forum_post']:+ output_url_file = args['Files']['output_last_forum_post_file']+ if output_url_file.exists():+ output_url_file.unlink()+ output_url_file.touch()- downloaders = await get_downloaders(content_object, excludes=excludes, SQL_helper=SQL_helper, client=client,- max_workers=threads, file_args=file_args, runtime_args=runtime_args,- pixeldrain_api_key=pixeldrain_api_key, scraper=backup_scraper)- for downloader in downloaders:- await downloader.download_content()+async def consolidate_links(args: dict, links: list) -> list:+ """We consolidate links from command line and from URLs.txt into a singular list"""+ links = list(map(URL, links))+ with open(args["Files"]["input_file"], "r", encoding="utf8") as f:+ links += await regex_links([line.rstrip() for line in f])+ links = list(filter(None, links))+ if not links:+ await log("[red]No valid links found.[/red]")+ exit(1)+ return links-async def director(args: argparse.Namespace):- await clear()- await log(f"We are running version {VERSION} of Cyberdrop Downloader", Fore.WHITE)- auth_args, file_args, jdownloader_args, runtime_args = await handle_args(args)+async def scrape_links(scraper: ScrapeMapper, links: list, quiet=False) -> CascadeItem:+ await log("[green]Starting Scrape[/green]", quiet=quiet)+ tasks = []- input_file = file_args['input_file']- if not input_file.is_file():- input_file.touch()- await log(f"{input_file} created. Populate it and retry.")- exit(1)+ for link in links:+ tasks.append(scraper.map_url(link))+ await asyncio.gather(*tasks)- client = Client(runtime_args['ratelimit'], runtime_args['throttle'])- SQL_helper = SQLHelper(runtime_args['ignore_history'], file_args['db_file'])- await SQL_helper.sql_initialize()+ Cascade = scraper.Cascade+ await Cascade.dedupe()+ Forums = scraper.Forums+ await Forums.dedupe()- threads = runtime_args['threads'] if runtime_args['threads'] != 0 else multiprocessing.cpu_count()+ await log("[green]Finished Scrape[/green]", quiet=quiet)+ return Cascade, Forums- links = args.links- links = list(map(URL, links))- with open(input_file, "r", encoding="utf8") as f:- links += await regex_links([line.rstrip() for line in f])- links = list(filter(None, links))+async def download(Cascade: CascadeItem, Forums: ForumItem):+ if not Cascade.is_empty():+ await log("[green]Downloading Loose Links[/green]")- if not links:- await log("No links found, check the URL.txt\nIf the link works in your web browser, "- "please open an issue ticket with me.", Fore.RED)+ if not Forums.is_empty():+ await log("[green]Downloading Forum Threads[/green]")- if runtime_args['output_last_forum_post']:- output_url_file = file_args['output_last_forum_post_file']- if output_url_file.exists():- output_url_file.unlink()- output_url_file.touch()- await download_all(auth_args=auth_args, file_args=file_args, jdownloader_args=jdownloader_args,- runtime_args=runtime_args, links=links, client=client, SQL_helper=SQL_helper, threads=threads)+async def director(args: dict, links: list) -> None:+ """This is the overarching director coordinator for CDL."""+ await clear()+ await document_args(args)+ await file_management(args, links)+ await log(f"We are running version {VERSION} of Cyberdrop Downloader")++ if not await check_free_space(args['Runtime']['required_free_space'], args['Files']['output_folder']):+ await log("[red]Not enough free space to continue. You can change the required space required using --required-free-space.[/red]")+ exit(1)++ links = await consolidate_links(args, links)+ client = Client(args['Ratelimiting']['ratelimit'], args['Ratelimiting']['throttle'], args['Runtime']['allow_insecure_connections'])+ SQL_Helper = SQLHelper(args['Ignore']['ignore_history'], args['Ignore']['ignore_cache'], args['Files']['db_file'])+ Scraper = ScrapeMapper(args, client, SQL_Helper, False)++ await SQL_Helper.sql_initialize()+ Cascade, Forums = await scrape_links(Scraper, links)+ await clear()+ if not await Cascade.is_empty():+ await download_cascade(args, Cascade, SQL_Helper, client, Scraper)+ if not await Forums.is_empty():+ await download_forums(args, Forums, SQL_Helper, client, Scraper)- logger.debug("Finished")+ # Do optional sort- partial_downloads = [str(f) for f in file_args['output_folder'].rglob("*.part") if f.is_file()]- temp_downloads_check = [str(f) for f in await SQL_helper.get_temp_names() if Path(f).is_file()]+ await log("")+ await log("Checking for incomplete downloads")+ partial_downloads = [str(f) for f in args['Files']['output_folder'].rglob("*.part") if f.is_file()]+ temp_downloads_check = [str(f) for f in await SQL_Helper.get_temp_names() if Path(f).is_file()]await log('Purging empty directories')- await purge_dir(file_args['output_folder'])+ await purge_dir(args['Files']['output_folder'])await log('Finished downloading. Enjoy :)')if partial_downloads:- await log('There are partial downloads in the downloads folder.')+ await log('[yellow]There are partial downloads in the downloads folder.[/yellow]')if temp_downloads_check:- await log('There are partial downloads from this run, please re-run the program.')+ await log('[yellow]There are partial downloads from this run, please re-run the program.[/yellow]')def main(args=None):if not args:args = parse_args()++ links = args.links+ args = run_args(args.config_file, argparse.Namespace(**vars(args)).__dict__)+logging.basicConfig(- filename=args.log_file,+ filename=args["Files"]["log_file"],level=logging.DEBUG,format="%(asctime)s:%(levelname)s:%(module)s:%(filename)s:%(lineno)d:%(message)s",filemode="w"@@ -209,7 +188,7 @@ def main(args=None):try:loop = asyncio.get_event_loop()- loop.run_until_complete(director(args))+ loop.run_until_complete(director(args, links))loop.run_until_complete(asyncio.sleep(5))except RuntimeError:passdiff --git a/cyberdrop_dl/scraper/JDownloader_Integration.py b/cyberdrop_dl/scraper/JDownloader_Integration.pynew file mode 100644index 000000000..c236946bf--- /dev/null+++ b/cyberdrop_dl/scraper/JDownloader_Integration.py@@ -0,0 +1,49 @@+import logging++from myjdapi import myjdapi+from yarl import URL++from cyberdrop_dl.base_functions.base_functions import log+from cyberdrop_dl.base_functions.error_classes import JDownloaderFailure+++class JDownloader:+ def __init__(self, jdownloader_args: dict, quiet: bool):+ self.jdownloader_device = jdownloader_args['jdownloader_device']+ self.jdownloader_username = jdownloader_args['jdownloader_username']+ self.jdownloader_password = jdownloader_args['jdownloader_password']++ self.jdownloader_enable = jdownloader_args['apply_jdownloader']+ self.jdownloader_agent = None+ self.quiet = quiet++ async def jdownloader_setup(self):+ try:+ if not self.jdownloader_username or not self.jdownloader_password or not self.jdownloader_device:+ raise JDownloaderFailure("jdownloader credentials were not provided.")+ jd = myjdapi.Myjdapi()+ jd.set_app_key("CYBERDROP-DL")+ jd.connect(self.jdownloader_username, self.jdownloader_password)+ self.jdownloader_agent = jd.get_device(self.jdownloader_device)+ except JDownloaderFailure:+ await log("[red]Failed JDownloader setup[/red]", quiet=self.quiet)+ self.jdownloader_enable = False++ async def direct_unsupported_to_jdownloader(self, url: URL, title: str):+ if self.jdownloader_enable:+ if not self.jdownloader_agent:+ await self.jdownloader_setup()+ try:+ if "facebook" in url.host.lower() or "instagram" in url.host.lower():+ raise JDownloaderFailure("Blacklisted META")++ self.jdownloader_agent.linkgrabber.add_links([{+ "autostart": False,+ "links": str(url),+ "packageName": title if title else "Cyberdrop-DL",+ "overwritePackagizerRules": True+ }])++ except JDownloaderFailure as e:+ logging.debug(e)+ await log("[red]Failed to send " + str(url) + " to JDownloader[/red]", quiet=self.quiet)diff --git a/cyberdrop_dl/scraper/Scraper.py b/cyberdrop_dl/scraper/Scraper.pynew file mode 100644index 000000000..62ef258c8--- /dev/null+++ b/cyberdrop_dl/scraper/Scraper.py@@ -0,0 +1,138 @@+import asyncio+import logging+from typing import Dict++import aiofiles+from yarl import URL++from cyberdrop_dl.base_functions.base_functions import log+from cyberdrop_dl.base_functions.data_classes import SkipData, CascadeItem, ForumItem, AlbumItem+from cyberdrop_dl.base_functions.sql_helper import SQLHelper+from cyberdrop_dl.client.client import Client, ScrapeSession+from cyberdrop_dl.client.rate_limiting import AsyncRateLimiter+from cyberdrop_dl.crawlers.Anonfiles_Spider import AnonfilesCrawler+from cyberdrop_dl.crawlers.Bunkr_Spider import BunkrCrawler+from cyberdrop_dl.crawlers.Cyberdrop_Spider import CyberdropCrawler+from cyberdrop_dl.crawlers.Xenforo_Spider import XenforoCrawler+from cyberdrop_dl.scraper.JDownloader_Integration import JDownloader+++class ScrapeMapper:+ def __init__(self, args: Dict, client: Client, SQL_Helper: SQLHelper, quiet: bool):+ self.args = args+ self.client = client+ self.SQL_Helper = SQL_Helper+ self.Cascade = CascadeItem({})+ self.Forums = ForumItem({})+ self.skip_data = SkipData(args['Ignore']['skip_hosts'])++ self.anonfiles_crawler = None+ self.bunkr_crawler = None+ self.cyberdrop_crawler = None+ self.coomer_crawler = None+ self.cyberfile_crawler = None+ self.erome_crawler = None+ self.fapello_crawler = None+ self.gfycat_crawler = None+ self.gofile_crawler = None+ self.hgamecg_crawler = None+ self.imgbox_crawler = None+ self.pixeldrain_crawler = None+ self.postimg_crawler = None+ self.redgifs_crawler = None+ self.rule34_crawler = None+ self.saint_crawler = None+ self.sharex_crawler = None+ self.xbunkr_crawler = None+ self.xenforo_crawler = None++ self.include_id = args['Runtime']['include_id']+ self.quiet = quiet+ self.jdownloader = JDownloader(args['JDownloader'], quiet)++ self.jpgchurch_limiter = AsyncRateLimiter(15)+ self.jpgchurch_semaphore = asyncio.Semaphore(5)+ self.bunkr_limiter = AsyncRateLimiter(15)+ self.forum_limiter = asyncio.Semaphore(4)+ self.semaphore = asyncio.Semaphore(1)++ self.mapping = {"anonfiles.com": self.Anonfiles, "bunkr": self.Bunkr, "cyberdrop": self.Cyberdrop,+ "simpcity": self.Xenforo, "socialmediagirls": self.Xenforo, "xbunker": self.Xenforo}++ async def handle_additions(self, domain: str, album_obj: AlbumItem, title=None):+ if title:+ await album_obj.append_title(title)+ await self.Forums.add_album_to_thread(title, domain, album_obj)+ else:+ await self.Cascade.add_album(domain, album_obj.title, album_obj)++ """Regular filehost handling"""++ async def Anonfiles(self, url: URL, title=None):+ anonfiles_session = ScrapeSession(self.client)+ if not self.anonfiles_crawler:+ self.anonfiles_crawler = AnonfilesCrawler(quiet=self.quiet, SQL_Helper=self.SQL_Helper)+ album_obj = await self.anonfiles_crawler.fetch(anonfiles_session, url)+ await self.handle_additions("anonfiles", album_obj, title)+ await anonfiles_session.exit_handler()++ async def Bunkr(self, url: URL, title=None):+ bunkr_session = ScrapeSession(self.client)+ if not self.bunkr_crawler:+ self.bunkr_crawler = BunkrCrawler(quiet=self.quiet, SQL_Helper=self.SQL_Helper)+ async with self.bunkr_limiter:+ album_obj = await self.bunkr_crawler.fetch(bunkr_session, url)+ if not await album_obj.is_empty():+ await self.handle_additions("bunkr", album_obj, title)+ await bunkr_session.exit_handler()++ async def Cyberdrop(self, url: URL, title=None):+ cyberdrop_session = ScrapeSession(self.client)+ if not self.cyberdrop_crawler:+ self.bunkr_crawler = CyberdropCrawler(include_id=self.include_id, quiet=self.quiet, SQL_Helper=self.SQL_Helper)+ album_obj = await self.bunkr_crawler.fetch(cyberdrop_session, url)+ await self.handle_additions("cyberdrop", album_obj, title)+ await cyberdrop_session.exit_handler()++ """Archive Sites"""++ """Forum handling"""++ async def Xenforo(self, url: URL, title=None):+ xenforo_session = ScrapeSession(self.client)+ if not self.xenforo_crawler:+ self.xenforo_crawler = XenforoCrawler(scraping_mapper=self, args=self.args, SQL_Helper=self.SQL_Helper,+ quiet=self.quiet)+ async with self.forum_limiter:+ cascade, title = await self.xenforo_crawler.fetch(xenforo_session, url)+ if not title or await cascade.is_empty():+ await xenforo_session.exit_handler()+ return+ await self.Forums.add_thread(title, cascade)+ await xenforo_session.exit_handler()++ async def map_url(self, url_to_map: URL, title=None):+ if not url_to_map:+ return+ elif not url_to_map.host:+ await log(f"[yellow]Not Supported: {str(url_to_map)}[/yellow]", quiet=self.quiet)+ return+ for key, value in self.mapping.items():+ if key in url_to_map.host:+ if any(site in key for site in self.skip_data.sites):+ await log(f"[yellow]Skipping: {str(url_to_map)}[/yellow]", quiet=self.quiet)+ else:+ await value(url=url_to_map, title=title)+ return++ if self.jdownloader.jdownloader_enable:+ async with asyncio.Semaphore(1):+ self.jdownloader.quiet = self.quiet+ if not self.jdownloader.jdownloader_agent:+ await self.jdownloader.jdownloader_setup()+ await self.jdownloader.direct_unsupported_to_jdownloader(url_to_map, title)++ else:+ await log(f"[yellow]Not Supported: {str(url_to_map)}[/yellow]", quiet=self.quiet)+ async with aiofiles.open(self.args["Files"]["unsupported_urls_file"], mode='a') as f:+ await f.write(str(url_to_map)+"\n")diff --git a/cyberdrop_dl/scraper/scraper.py b/cyberdrop_dl/scraper/scraper.pydeleted file mode 100644index 04dbb90ad..000000000--- a/cyberdrop_dl/scraper/scraper.py+++ /dev/null@@ -1,29 +0,0 @@-import asyncio-from typing import Dict--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, file_args: Dict, jdownloader_args: Dict, runtime_args: Dict,- jdownloader_auth: AuthData, simpcity_auth: AuthData, socialmediagirls_auth: AuthData,- xbunker_auth: AuthData, skip_data: SkipData, quiet=False, close=True):- await log("Starting Scrape", quiet=quiet)-- scraper = ScrapeMapper(client=client, file_args=file_args, jdownloader_args=jdownloader_args,- runtime_args=runtime_args, xbunker_auth=xbunker_auth,- socialmediagirls_auth=socialmediagirls_auth, simpcity_auth=simpcity_auth,- jdownloader_auth=jdownloader_auth, skip_data=skip_data, quiet=quiet)- tasks = []- for link in urls:- tasks.append(scraper.map_url(link))- await asyncio.gather(*tasks)-- if close:- await scraper.close()-- Cascade = scraper.Cascade- await Cascade.dedupe()- return Cascadediff --git a/cyberdrop_dl/scraper/scraper_helper.py b/cyberdrop_dl/scraper/scraper_helper.pydeleted file mode 100644index c038f8bad..000000000--- a/cyberdrop_dl/scraper/scraper_helper.py+++ /dev/null@@ -1,398 +0,0 @@-import asyncio-import logging-from typing import Dict--import aiofiles-from myjdapi import myjdapi-from yarl import URL--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.Fapello_Spider import FapelloCrawler-from ..crawlers.Gfycat_Spider import GfycatCrawler-from ..crawlers.GoFile_Spider import GofileCrawler-from ..crawlers.HGameCG_Spider import HGameCGCrawler-from ..crawlers.ImgBox_Spider import ImgBoxCrawler-from ..crawlers.Kemono_Spider import KemonoCrawler-from ..crawlers.Pixeldrain_Spider import PixelDrainCrawler-from ..crawlers.Postimg_Spider import PostImgCrawler-from ..crawlers.Redgifs_Spider import RedGifsCrawler-from ..crawlers.Rule34_Spider import Rule34Crawler-from ..crawlers.Saint_Spider import SaintCrawler-from ..crawlers.ShareX_Spider import ShareXCrawler-from ..crawlers.SocialMediaGirls_Spider import SocialMediaGirlsCrawler-from ..crawlers.SimpCity_Spider import SimpCityCrawler-from ..crawlers.XBunker_Spider import XBunkerCrawler-from ..crawlers.XBunkr_Spider import XBunkrCrawler-from ..base_functions.base_functions import log-from ..base_functions.data_classes import CascadeItem, SkipData, AuthData-from ..client.rate_limiting import AsyncRateLimiter---class ScrapeMapper:- def __init__(self, *, client: Client, file_args: Dict, jdownloader_args: Dict, runtime_args: Dict,- jdownloader_auth: AuthData, simpcity_auth: AuthData, socialmediagirls_auth: AuthData,- xbunker_auth: AuthData, skip_data: SkipData, quiet: bool):-- self.include_id = runtime_args['include_id']- self.quiet = quiet- self.jdownloader_enable = jdownloader_args['jdownloader_enable']- self.jdownloader_device = jdownloader_args['jdownloader_device']- self.separate_posts = runtime_args['separate_posts']- self.output_last = [runtime_args['output_last_forum_post'], file_args['output_last_forum_post_file']]- self.xbunker_auth = xbunker_auth- self.socialmediagirls_auth = socialmediagirls_auth- self.simpcity_auth = simpcity_auth- self.jdownloader_auth = jdownloader_auth-- self.client = client- self.Cascade = CascadeItem({})- self.skip_data = skip_data-- self.anonfiles_crawler = None- self.bunkr_crawler = None- self.cyberdrop_crawler = None- self.coomer_crawler = None- self.cyberfile_crawler = None- self.erome_crawler = None- self.fapello_crawler = None- self.gfycat_crawler = None- self.gofile_crawler = None- self.hgamecg_crawler = None- self.imgbox_crawler = None- self.pixeldrain_crawler = None- self.postimg_crawler = None- self.redgifs_crawler = None- self.rule34_crawler = None- self.saint_crawler = None- self.sharex_crawler = None- self.socialmediagirls_crawler = None- self.simpcity_crawler = None- self.xbunker_crawler = None- self.xbunkr_crawler = None-- self.jdownloader_agent = None-- self.jpgchurch_limiter = AsyncRateLimiter(15)- self.jpgchurch_semaphore = asyncio.Semaphore(5)- self.bunkr_limiter = AsyncRateLimiter(15)- self.forum_limiter = asyncio.Semaphore(4)- self.semaphore = asyncio.Semaphore(1)-- self.crawlers = [self.anonfiles_crawler, self.bunkr_crawler, self.cyberdrop_crawler, self.coomer_crawler,- self.cyberfile_crawler, self.erome_crawler, self.gfycat_crawler, self.gofile_crawler,- self.hgamecg_crawler, self.imgbox_crawler, self.pixeldrain_crawler,- self.postimg_crawler, self.redgifs_crawler, self.rule34_crawler, self.saint_crawler,- self.sharex_crawler, self.socialmediagirls_crawler, self.simpcity_crawler,- self.xbunker_crawler, self.xbunkr_crawler]-- self.mapping = {"anonfiles.com": self.Anonfiles, "xbunkr": self.XBunkr,- "bunkr": self.Bunkr, "coomer.party": self.Coomer, "cyberdrop": self.Cyberdrop,- "cyberfile.is": self.Cyberfile, "cyberfile.su": self.Cyberfile, "erome.com": self.Erome,- "fapello": self.Fapello, "gfycat.com": self.Gfycat, "gofile.io": self.GoFile,- "hgamecg.com": self.HGameCG, "imgbox.com": self.ImgBox, "img.kiwi": self.ShareX,- "jpg.church": self.ShareX, "pixeldrain.com": self.Pixeldrain,- "pixl.li": self.ShareX, "postimg": self.Postimg, "redgifs.com": self.Redgifs,- "rule34.xxx": self.Rule34, "saint.to": self.Saint, "socialmediagirls": self.SocialMediaGirls,- "simpcity": self.SimpCity, "xbunker": self.XBunker}-- 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, quiet=self.quiet)- 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, quiet=self.quiet)- async with self.bunkr_limiter:- 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, quiet=self.quiet)- 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, scraping_mapper=self,- separate_posts=self.separate_posts, quiet=self.quiet)- 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(quiet=self.quiet)- async with self.semaphore:- 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, quiet=self.quiet)- 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 Fapello(self, url: URL, title=None):- fapello_session = Session(self.client)- if not self.fapello_crawler:- self.fapello_crawler = FapelloCrawler(include_id=self.include_id, quiet=self.quiet)- domain_obj = await self.fapello_crawler.fetch(fapello_session, url)- if title:- await domain_obj.append_title(title)- await self.Cascade.add_albums(domain_obj)- await fapello_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(quiet=self.quiet)- except SystemExit as e:- logging.debug(e)- await log("Couldn't start the GoFile crawler", quiet=self.quiet)- return- 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 HGameCG(self, url: URL, title=None):- hgamecg_session = Session(self.client)- if not self.hgamecg_crawler:- self.hgamecg_crawler = HGameCGCrawler(quiet=self.quiet)- domain_obj = await self.hgamecg_crawler.fetch(hgamecg_session, url)- if title:- await domain_obj.append_title(title)- await self.Cascade.add_albums(domain_obj)- await hgamecg_session.exit_handler()-- async def ImgBox(self, url: URL, title=None):- imgbox_session = Session(self.client)- if not self.imgbox_crawler:- self.imgbox_crawler = ImgBoxCrawler(include_id=self.include_id, quiet=self.quiet)- domain_obj = await self.imgbox_crawler.fetch(imgbox_session, url)- if title:- await domain_obj.append_title(title)- await self.Cascade.add_albums(domain_obj)- await imgbox_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, scraping_mapper=self,- # separate_posts=self.separate_posts, quiet=self.quiet)- # 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(quiet=self.quiet)- 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(quiet=self.quiet)- 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 Postimg(self, url: URL, title=None):- postimg_session = Session(self.client)- if not self.postimg_crawler:- self.postimg_crawler = PostImgCrawler(include_id=self.include_id, quiet=self.quiet)- domain_obj = await self.postimg_crawler.fetch(postimg_session, url)- if title:- await domain_obj.append_title(title)- await self.Cascade.add_albums(domain_obj)- await postimg_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(quiet=self.quiet)- 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 Rule34(self, url: URL, title=None):- rule34_session = Session(self.client)- if not self.rule34_crawler:- self.rule34_crawler = Rule34Crawler(quiet=self.quiet)- domain_obj = await self.rule34_crawler.fetch(rule34_session, url)-- if title:- await domain_obj.append_title(title)- await self.Cascade.add_albums(domain_obj)-- await rule34_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, quiet=self.quiet)- 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, quiet=self.quiet)- if "jpg.church" in url.host and sharex_session.client.ratelimit > 19:- async with self.jpgchurch_semaphore:- async with self.jpgchurch_limiter:- domain_obj = await self.sharex_crawler.fetch(sharex_session, url)- else:- 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)- await sharex_session.exit_handler()-- async def SocialMediaGirls(self, url: URL, title=None):- socialmediagirls_session = Session(self.client)- if not self.socialmediagirls_crawler:- self.socialmediagirls_crawler = SocialMediaGirlsCrawler(include_id=self.include_id,- auth=self.socialmediagirls_auth,- scraping_mapper=self,- separate_posts=self.separate_posts,- output_last=self.output_last, quiet=self.quiet)- async with self.forum_limiter:- await self.Cascade.extend(await self.socialmediagirls_crawler.fetch(socialmediagirls_session, url))- await socialmediagirls_session.exit_handler()-- async def SimpCity(self, url: URL, title=None):- simpcity_session = Session(self.client)- if not self.simpcity_crawler:- self.simpcity_crawler = SimpCityCrawler(include_id=self.include_id, auth=self.simpcity_auth,- scraping_mapper=self, separate_posts=self.separate_posts,- output_last=self.output_last, quiet=self.quiet)- async with self.forum_limiter:- await self.Cascade.extend(await self.simpcity_crawler.fetch(simpcity_session, url))- await simpcity_session.exit_handler()-- async def XBunker(self, url: URL, title=None):- xbunker_session = Session(self.client)- if not self.xbunker_crawler:- self.xbunker_crawler = XBunkerCrawler(include_id=self.include_id, auth=self.xbunker_auth,- scraping_mapper=self, separate_posts=self.separate_posts,- output_last=self.output_last, quiet=self.quiet)- async with self.forum_limiter:- await self.Cascade.extend(await self.xbunker_crawler.fetch(xbunker_session, url))- await xbunker_session.exit_handler()-- async def XBunkr(self, url: URL, title=None):- xbunkr_session = Session(self.client)- if not self.xbunkr_crawler:- self.xbunkr_crawler = XBunkrCrawler(include_id=self.include_id, quiet=self.quiet)- domain_obj = await self.xbunkr_crawler.fetch(xbunkr_session, url)- if title:- await domain_obj.append_title(title)- await self.Cascade.add_albums(domain_obj)- await xbunkr_session.exit_handler()-- async def jdownloader_setup(self):- try:- if not self.jdownloader_auth.username or not self.jdownloader_auth.password or not self.jdownloader_device:- raise Exception("jdownloader credentials were not provided.")- jd = myjdapi.Myjdapi()- jd.set_app_key("CYBERDROP-DL")- jd.connect(self.jdownloader_auth.username, self.jdownloader_auth.password)- self.jdownloader_agent = jd.get_device(self.jdownloader_device)- except:- await log("Failed jdownloader setup", quiet=self.quiet)- self.jdownloader_enable = False-- async def close(self):- for crawler in self.crawlers:- crawler = None--- async def map_url(self, url_to_map: URL, title=None):- if not url_to_map:- return- elif not url_to_map.host:- await log(str(url_to_map) + " is not supported currently.", quiet=self.quiet)- return- for key, value in self.mapping.items():- if key in url_to_map.host:- if any(site in key for site in self.skip_data.sites):- await log("Skipping scrape of " + str(url_to_map), quiet=self.quiet)- else:- await value(url=url_to_map, title=title)- return-- if self.jdownloader_enable:- if not self.jdownloader_agent:- await self.jdownloader_setup()- try:- if "facebook" in url_to_map.host.lower() or "instagram" in url_to_map.host.lower():- raise Exception("Blacklisted META")- await log("Sending " + str(url_to_map) + " to JDownloader", quiet=self.quiet)- self.jdownloader_agent.linkgrabber.add_links([{- "autostart": False,- "links": str(url_to_map),- "packageName": title if title else "Cyberdrop-DL",- "overwritePackagizerRules": True- }])- except Exception as e:- logging.debug(e)- await log("Failed to send " + str(url_to_map) + " to JDownloader", quiet=self.quiet)- else:- await log("Not Supported: " + str(url_to_map), quiet=self.quiet)- async with aiofiles.open("./Unsupported_Urls.txt", mode='a') as f:- await f.write(str(url_to_map)+"\n")diff --git a/requirements.txt b/requirements.txtindex c8fc994e3..a1e96f34b 100644--- a/requirements.txt+++ b/requirements.txt@@ -1,12 +1,9 @@-aiofiles==22.1.0-aiohttp==3.8.3-beautifulsoup4==4.11.1-certifi==2022.12.7-colorama==0.4.6-gofile_client==1.0.1-myjdapi==1.1.6-PyYAML==6.0-psutil~=5.9.4-setuptools==65.6.3-tqdm==4.64.1-yarl==1.8.2\ No newline at end of file+yarl~=1.8.2+PyYAML~=6.0+aiofiles~=22.1.0+aiohttp~=3.8.3+certifi~=2022.12.7+beautifulsoup4==4.11.2+rich~=13.3.1+myjdapi~=1.1.6+psutil~=5.9.4\ No newline at end of filediff --git a/setup.cfg b/setup.cfgindex 9e83a3e11..6c67b694a 100644--- a/setup.cfg+++ b/setup.cfg@@ -3,7 +3,7 @@ name = cyberdrop-dlversion = attr: cyberdrop_dl.__version__author = Jules-WinnfieldXauthor_email = [email protected]-description = Bulk downloader for multiple file hosts+description = Bulk downloader for multiple file hosts and forum siteslong_description = file: README.mdlong_description_content_type = text/markdownurl = https://github.com/Jules-WinnfieldX/CyberDropDownloader@@ -17,15 +17,12 @@ packages = find:install_requires =aiofiles>=22.1.0aiohttp>=3.8.3- beautifulsoup4>=4.11.1+ beautifulsoup4>=4.11.2certifi>=2022.12.7- colorama>=0.4.6- gofile_client>=1.0.1myjdapi>=1.1.6PyYAML>=6.0psutil>=5.9.4setuptools>=65.6.3- tqdm>=4.64.1yarl>=1.8.2[options.entry_points]