Bulk asynchronous downloader for multiple file hosts
Python asynciobunkrcyberdropdownloaderdropboxfilestergofilegoogle-drivemediafiremegamega-nzonedrivepatreonpawchivepinterestpixeldraintransfer-ittwitchtwittervk
Finish changing to async with aiohttp, dataclass
Jules-WinnfieldX216703537b7a
diff --git a/cyberdrop_dl/main.py b/cyberdrop_dl/main.pyindex adca0a9c5..b555d9363 100644--- a/cyberdrop_dl/main.py+++ b/cyberdrop_dl/main.py@@ -6,7 +6,6 @@ from pathlib import Pathimport refrom colorama import Fore, Style-import nest_asyncioimport requestsfrom . import __version__ as VERSION@@ -15,13 +14,6 @@ from .utils.downloaders import get_downloadersfrom .utils.data_classes import *-# Fixes reactor already installed error (issue using Scrapy with Asyncio)-try:- asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())-except Exception:- pass--def parse_args():parser = argparse.ArgumentParser(description="Bulk downloader for multiple file hosts")parser.add_argument("-V", "--version", action="version", version="%(prog)s " + VERSION)@@ -52,7 +44,6 @@ def regex_links(urls) -> list:async def download_all(args: argparse.Namespace):- nest_asyncio.apply()clear()log(f"We are running version {VERSION} of Cyberdrop Downloader", Fore.WHITE)logging.debug(f"Starting downloader with args: {args.__dict__}")@@ -73,7 +64,7 @@ async def download_all(args: argparse.Namespace):raise ValueError('No links found, check the URL.txt\nIf the link works in your web browser, ''please open an issue ticket with me.')clear()- downloaders = get_downloaders(content_object, cookies=cookies, folder=Path(args.output_folder), attempts=args.attempts, threads=args.threads)+ downloaders = get_downloaders(content_object, cookies=content_object.cookies.cookies, folder=Path(args.output_folder), attempts=args.attempts, threads=args.threads)for downloader in downloaders:await downloader.download_content()diff --git a/cyberdrop_dl/utils/base_functions.py b/cyberdrop_dl/utils/base_functions.pyindex 239ab07b7..243d2a8a7 100644--- a/cyberdrop_dl/utils/base_functions.py+++ b/cyberdrop_dl/utils/base_functions.py@@ -37,7 +37,8 @@ def bunkr_parse(url: str) -> str:"""Fix the URL for bunkr.is."""extension = '.' + url.split('.')[-1]if extension.lower() in FILE_FORMATS['Videos']:- changed_url = url.replace('cdn.bunkr', 'media-files.bunkr').split('/')+ changed_url = url.replace('cdn.bunkr', 'media-files.bunkr')+ changed_url = changed_url.replace('stream.bunkr.is/v/', 'media-files.bunkr.is/').split('/')changed_url = ''.join(map(lambda x: urljoin('/', x), changed_url))return changed_urlif extension.lower() in FILE_FORMATS['Images']:diff --git a/cyberdrop_dl/utils/crawlers/Chibisafe_Spider.py b/cyberdrop_dl/utils/crawlers/Chibisafe_Spider.pyindex 75b496dc5..b696cd039 100644--- a/cyberdrop_dl/utils/crawlers/Chibisafe_Spider.py+++ b/cyberdrop_dl/utils/crawlers/Chibisafe_Spider.py@@ -1,64 +1,46 @@-import re-from urllib.parse import urljoin, urlparse+import logging-from scrapy import Spider-from scrapy.http.request import Request-import aiohttp+import tldextractfrom bs4 import BeautifulSoup-from ..data_classes import *from ..base_functions import *+from ..data_classes import *-class ChibisafeCrawler():- def __init__(self, **kwargs):- self.links: list[str] = kwargs.get("links", [])- self.include_id = kwargs.get('include_id', False)- self.results = {}----class Chibisafe_Spider(Spider):- name = 'Chibisafe'-- def __init__(self, *args, **kwargs):- self.myurls = kwargs.get('myurls', [])- self.include_id = kwargs.get('include_id', False)- super(Chibisafe_Spider, self).__init__(*args, **kwargs)-- def start_requests(self):- for url in self.myurls:- ext = "." + url.split('.')[-1]- if '/a/' in url:- yield Request(url, self.parse)- elif ext in FILE_FORMATS['Images']:- yield Request(url, self.individual_file)- elif ext in FILE_FORMATS['Videos']:- yield Request(url, self.individual_bunkr_video, meta={'dont_redirect': True, 'handle_httpstatus_list': [301, 302]})+logger = logging.getLogger(__name__)- def individual_file(self, response):- netloc = urlparse(response.url).netloc.replace('www.', '')- title = "Chibisafe Loose Files"- yield {'netloc': netloc, 'url': bunkr_parse(response.url), 'title': title, 'referal': response.url, 'cookies': ''}- def individual_bunkr_video(self, response):- netloc = urlparse(response.url).netloc.replace('www.', '')- title = "Chibisafe Loose Files"- link = response.url.replace('stream.bunkr.is/v/', 'media-files.bunkr.is/')- yield {'netloc': netloc, 'url': bunkr_parse(link), 'title': title, 'referal': response.url, 'cookies': ''}+class ChibisafeCrawler():+ def __init__(self, *, include_id=False, **kwargs):+ self.include_id = include_id- def parse(self, response, **kwargs):- links = response.css('a[class=image]::attr(href)').getall()+ async def fetch(self, session, url):+ url_extract = tldextract.extract(url)+ base_domain = "{}.{}".format(url_extract.domain, url_extract.suffix)+ domain_obj = DomainItem(base_domain, {})+ cookies = []try:- title = response.css('h1[id=title]::text').get()- title = title.replace(r"\n", "").strip()- if self.include_id:- title = title + " - " + response.url.split('/')[-1]+ async with session.get(url) as response:+ text = await response.text()+ soup = BeautifulSoup(text, 'html.parser')++ title = soup.select_one("h1[id=title]").get_text()+ if title is None:+ title = response.url.split('/')[-1]+ elif self.include_id:+ titlep2 = response.url.split('/')+ titlep2 = [s for s in titlep2 if "." in s][-1]+ title = title + " - " + titlep2+ title = make_title_safe(title.replace(r"\n", "").strip())++ links = soup.select("a[class=image]")+ for link in links:+ link = link.get('href')+ domain_obj.add_to_album(title, link, url)+except Exception as e:- title = response.url.split('/')[-1]- title = re.sub(r'[/]', "-", title)+ logger.debug("Error encountered while handling %s", url, exc_info=True)+ logger.debug(e)- for link in links:- netloc = urlparse(link).netloc.replace('www.', '')- yield {'netloc': netloc, 'url': bunkr_parse(link), 'title': title, 'referal': response.url, 'cookies': ''}+ return domain_obj, cookiesdiff --git a/cyberdrop_dl/utils/crawlers/Erome_Spider.py b/cyberdrop_dl/utils/crawlers/Erome_Spider.pyindex 33cfd8f3f..16b64e0a3 100644--- a/cyberdrop_dl/utils/crawlers/Erome_Spider.py+++ b/cyberdrop_dl/utils/crawlers/Erome_Spider.py@@ -3,7 +3,8 @@ import loggingimport tldextractfrom bs4 import BeautifulSoup-from .. import base_functions, data_classes+from ..base_functions import *+from ..data_classes import *logger = logging.getLogger(__name__)@@ -16,7 +17,7 @@ class EromeCrawler():async def fetch(self, session, url):url_extract = tldextract.extract(url)base_domain = "{}.{}".format(url_extract.domain, url_extract.suffix)- domain_obj = data_classes.DomainItem(base_domain, {})+ domain_obj = DomainItem(base_domain, {})cookies = []try:@@ -30,7 +31,7 @@ class EromeCrawler():title = response.url.split('/')[-1]elif self.include_id:title = title + " - " + url.split('/')[-1]- title = base_functions.make_title_safe(title)+ title = make_title_safe(title)# Imagesfor link in soup.select('img[class="img-front lasyload"]'):diff --git a/cyberdrop_dl/utils/crawlers/GoFile_Spider.py b/cyberdrop_dl/utils/crawlers/GoFile_Spider.pyindex ef8894aa6..60989cc61 100644--- a/cyberdrop_dl/utils/crawlers/GoFile_Spider.py+++ b/cyberdrop_dl/utils/crawlers/GoFile_Spider.py@@ -2,29 +2,38 @@ from typing import Unionfrom gofile import Gofile+from ..base_functions import *+from ..data_classes import *+class GofileCrawler():def __init__(self, **kwargs):self.client = Gofile()- self.links: list[str] = kwargs.get("links", [])-- def build_targets(self, targets={}, **kwargs):- links = kwargs.get("links", self.links)- for link in links:- content_id = link.split("/")[-1] if link.startswith("https://gofile.io/") else link- content = self.client.get_content(content_id)- if not content:- continue-- title = content["name"]- targets[title] = []- contents: dict[str, dict[str, Union[str, int]]] = content["contents"]- for val in contents.values():- if val["type"] == "folder":- self.build_targets(targets, links=[val["code"]])- else:- targets[title].append([- val["link"] if val["link"] != "overloaded" else val["directLink"],- 'https://gofile.io/',- ])- return targets++ async def fetch(self, url):+ domain_obj = DomainItem('gofile.io', {})+ cookies = [{'name': 'accountToken', 'value': self.client.token}]+ results = await self.get_links(url)+ for result in results:+ domain_obj.add_to_album(result['title'], result['url'], result['referral'])+ return domain_obj, cookies++ async def get_links(self, url, og_title=None):+ results = []+ content_id = url.split("/")[-1] if url.startswith("https://gofile.io/") else url+ content = self.client.get_content(content_id)+ 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":+ results.extend(result for result in await self.get_links(val["code"], title))+ else:+ results.append({'url': val["link"] if val["link"] != "overloaded" else val["directLink"],+ 'title': title, 'referral': 'https://gofile.io/'})+ return resultsdiff --git a/cyberdrop_dl/utils/crawlers/ShareX_Spider.py b/cyberdrop_dl/utils/crawlers/ShareX_Spider.pyindex a418a89c3..fe54b28f3 100644--- a/cyberdrop_dl/utils/crawlers/ShareX_Spider.py+++ b/cyberdrop_dl/utils/crawlers/ShareX_Spider.py@@ -1,99 +1,154 @@-import re-from urllib.parse import urlparse--from scrapy import Spider-from scrapy.http.request import Request--class ShareX_Spider(Spider):- name = 'ShareX'-- def __init__(self, *args, **kwargs):- self.myurls = kwargs.get('myurls', [])- self.include_id = kwargs.get('include_id', False)- super(ShareX_Spider, self).__init__(*args, **kwargs)-- def start_requests(self):- for url in self.myurls:- if '/album/' in url or '/a/' in url:- yield Request(url, self.parse)- elif '/albums' in url:- yield Request(url, self.get_albums)- elif '/image/' in url or '/img/' in url or '/images/' in url:- yield Request(url, self.get_singular)- else:- yield Request(url, self.parse_profile)-- def parse_profile(self, response):+import logging++import tldextract+from bs4 import BeautifulSoup++from ..base_functions import *+from ..data_classes import *+++logger = logging.getLogger(__name__)+++class ShareXCrawler():+ def __init__(self, *, include_id=False, **kwargs):+ self.include_id = include_id++ async def fetch(self, session, url):+ url_extract = tldextract.extract(url)+ base_domain = "{}.{}".format(url_extract.domain, url_extract.suffix)+ domain_obj = DomainItem(base_domain, {})+ cookies = []++ if "/album/" in url or "/a/" in url:+ results = await self.parse(url, session)+ elif "/albums" in url:+ results = await self.get_albums(url, session)+ elif '/image/' in url or '/img/' in url or '/images/' in url:+ results = await self.get_singular(url, session)+ else:+ results = await self.parse_profile(url, session)+ for result in results:+ domain_obj.add_to_album(result['title'], result['url'], result['referral'])+ return domain_obj, cookies++ async def get_albums(self, url, session):+ results = []try:- title = response.css('div[class=header] h1 strong::text').get()- title = title.replace(r"\n", "").strip()- if self.include_id:- titlep2 = response.url.split('/')- titlep2 = [s for s in titlep2 if "." in s][-1]- title = title + " - " + titlep2+ async with session.get(url) as response:+ text = await response.text()+ soup = BeautifulSoup(text, 'html.parser')+ albums = soup.select("a[class='image-container --media']")+ for album in albums:+ album_url = album.get('href')+ results.extend(result for result in await self.parse(album_url, session))except Exception as e:- title = response.url.split('/')- title = [s for s in title if "." in s][-1]- title = re.sub(r'[/]', "-", title)+ logger.debug("Error encountered while handling %s", url, exc_info=True)+ logger.debug(e)+ return results- list_recent = response.css('a[id=list-most-recent-link]::attr(href)').get()- yield Request(list_recent, callback=self.get_list_links, meta={'title': title})+ async def get_singular(self, url, session):+ results = []+ try:+ async with session.get(url) as response:+ text = await response.text()+ soup = BeautifulSoup(text, 'html.parser')+ link = soup.select_one("input[id=embed-code-2]").get('value')+ link = link.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", url, exc_info=True)+ logger.debug(e)+ return results- def get_albums(self, response):- albums = response.css("a[class='image-container --media']::attr(href)").getall()- for url in albums:- yield Request(url, callback=self.parse)+ async def get_sub_album_links(self, url, session, og_title):+ results = []+ try:+ async with session.get(url) as response:+ text = await response.text()+ soup = BeautifulSoup(text, 'html.parser')+ albums = soup.select("div[class=pad-content-listing] div")+ for album in albums:+ album_url = album.get('data-url-short')+ results.extend(result for result in await self.parse(album_url, session, og_title=og_title))+ except Exception as e:+ logger.debug("Error encountered while handling %s", url, exc_info=True)+ logger.debug(e)+ return results- def parse(self, response, **kwargs):+ async def parse_profile(self, url, session):+ results = []try:- title = response.css('a[data-text=album-name]::text').get()- title = title.replace(r"\n", "").strip()- if self.include_id:- titlep2 = response.url.split('/')- titlep2 = [s for s in titlep2 if "." in s][-1]- title = title + " - " + titlep2+ async with session.get(url) as response:+ text = await response.text()+ soup = BeautifulSoup(text, 'html.parser')+ title = soup.select_one("div[class=header] h1 strong").get_text()+ if title is None:+ title = response.url.split('/')+ title = [s for s in title if "." in s][-1]+ elif self.include_id:+ titlep2 = response.url.split('/')+ titlep2 = [s for s in titlep2 if "." in s][-1]+ title = title + " - " + titlep2+ title = make_title_safe(title.replace(r"\n", "").strip())++ list_recent = soup.select_one("a[id=list-most-recent-link]").get('href')+ results.extend(result for result in await self.get_list_links(list_recent, session, title))except Exception as e:- title = response.url.split('/')- title = [s for s in title if "." in s][-1]- title = re.sub(r'[/]', "-", title)+ logger.debug("Error encountered while handling %s", url, exc_info=True)+ logger.debug(e)+ return results+ async def get_list_links(self, url, session, title):+ results = []try:- title = response.meta.get('title') + "/" + title- except:- pass-- sub_albums = response.css('a[id=tab-sub-link]::attr(href)').get()- yield Request(sub_albums, callback=self.get_sub_albums_links, meta={'title': title}, dont_filter=True)-- list_recent = response.css('a[id=list-most-recent-link]::attr(href)').get()- yield Request(list_recent, callback=self.get_list_links, meta={'title': title})-- def get_singular(self, response):- link = response.css('input[id=embed-code-2]::attr(value)').get()- link = link.replace('.md.', '.').replace('.th.', '.')- title = "ShareX Loose Files"- netloc = urlparse(link).netloc.replace('www.', '')- yield {'netloc': netloc, 'url': link, 'title': title, 'referal': response.url, 'cookies': ''}-- def get_sub_albums_links(self, response):- albums = response.css('div[class=pad-content-listing] div::attr(data-url-short)').getall()- for album in albums:- yield Request(album, self.parse, meta=response.meta)-- def get_list_links(self, response):- links = response.meta.get('links', [])- if 'jpg.church' in response.url:- links.extend(response.css('a[href*=img] img::attr(src)').getall())- else:- links.extend(response.css('a[href*=image] img::attr(src)').getall())- title = response.meta.get('title')+ async with session.get(url) as response:+ text = await response.text()+ soup = BeautifulSoup(text, 'html.parser')+ if 'jpg.church' in url:+ links = soup.select("a[href*=img] img")+ else:+ links = soup.select("a[href*=image] img")+ for link in links:+ link = link.get('src')+ link = link.replace('.md.', '.').replace('.th.', '.')+ results.append({'url': link, 'title': title, 'referral': url, 'cookies': ''})+ next_page = soup.select_one('li.pagination-next a')+ if next_page is not None:+ next_page = next_page.get('href')+ results.extend(result for result in await self.get_list_links(next_page, session, title))+ except Exception as e:+ logger.debug("Error encountered while handling %s", url, exc_info=True)+ logger.debug(e)+ return results- next_page = response.css('li.pagination-next a::attr("href")').get()- meta = {'links': links, 'title': title}- if next_page is not None:- yield Request(url=next_page, callback=self.get_list_links, meta=meta)- else:- for link in links:- netloc = urlparse(link).netloc.replace('www.', '')- link = link.replace('.md.', '.').replace('.th.', '.')- yield {'netloc': netloc, 'url': link, 'title': title, 'referal': response.url, 'cookies': ''}+ async def parse(self, url, session, og_title=None):+ results = []+ try:+ async with session.get(url) as response:+ text = await response.text()+ soup = BeautifulSoup(text, 'html.parser')++ title = soup.select_one("a[data-text=album-name]").get_text()+ if title is None:+ title = response.url.split('/')[-1]+ elif self.include_id:+ titlep2 = response.url.split('/')+ titlep2 = [s for s in titlep2 if "." in s][-1]+ title = title + " - " + titlep2+ title = make_title_safe(title.replace(r"\n", "").strip())++ if og_title is not None:+ title = og_title + "/" + title++ sub_albums = soup.select_one("a[id=tab-sub-link]").get("href")+ results.extend(result for result in await self.get_sub_album_links(sub_albums, session, title))++ list_recent = soup.select_one("a[id=list-most-recent-link]").get("href")+ results.extend(result for result in await self.get_list_links(list_recent, session, title))++ except Exception as e:+ logger.debug("Error encountered while handling %s", url, exc_info=True)+ logger.debug(e)+ return results\ No newline at end of filediff --git a/cyberdrop_dl/utils/scraper.py b/cyberdrop_dl/utils/scraper.pyindex 7f0540dc0..fa05429b7 100644--- a/cyberdrop_dl/utils/scraper.py+++ b/cyberdrop_dl/utils/scraper.py@@ -8,9 +8,9 @@ import aiohttpimport tldextractfrom colorama import Fore, Style-from .crawlers.ShareX_Spider import ShareX_Spider+from .crawlers.ShareX_Spider import ShareXCrawlerfrom .crawlers.Erome_Spider import EromeCrawler-from .crawlers.Chibisafe_Spider import Chibisafe_Spider+from .crawlers.Chibisafe_Spider import ChibisafeCrawlerfrom .crawlers.GoFile_Spider import GofileCrawlerfrom .data_classes import *from .base_functions import *@@ -26,6 +26,7 @@ def log(text, style):async def scrape(urls, include_id: bool):Cascade = CascadeItem({})+ShareX_urls = []Chibisafe_urls = []Erome_urls = []@@ -65,16 +66,26 @@ async def scrape(urls, include_id: bool):Cascade.add_to_album(base_domain, title, pixeldrain_parse(url, title), url)# TODO entire thotsbay forum pages, scrape all images, embedded videos, scrape all links+else:unsupported_urls.append(url)erome_crawler = EromeCrawler(include_id=include_id)+ sharex_crawler = ShareXCrawler(include_id=include_id)+ chibisafe_crawler = ChibisafeCrawler(include_id=include_id)+ gofile_crawler = GofileCrawler()tasks = []headers = {"user-agent": user_agent}async with aiohttp.ClientSession(headers=headers, raise_for_status=True) as session:for url in Erome_urls:tasks.append(erome_crawler.fetch(session, url))+ for url in ShareX_urls:+ tasks.append(sharex_crawler.fetch(session, url))+ for url in Chibisafe_urls:+ tasks.append(chibisafe_crawler.fetch(session, url))+ for url in GoFile_urls:+ tasks.append(gofile_crawler.fetch(url))results = await asyncio.gather(*tasks)for item_pair in results:@@ -82,18 +93,4 @@ async def scrape(urls, include_id: bool):Cascade.add_albums(domain_item)Cascade.add_cookie(cookie_item)--- # if ShareX_urls:- # # process.crawl(ShareX_Spider, myurls=ShareX_urls, include_id=include_id)- # if Chibisafe_urls:- # # process.crawl(Chibisafe_Spider, myurls=Chibisafe_urls, include_id=include_id)- # if GoFile_urls:- # gofile_crawler = GofileCrawler(links=GoFile_urls, include_id=include_id)- # result_links.setdefault('gofile.io', gofile_crawler.build_targets())- # cookies.append({- # 'name': 'accountToken',- # 'value': gofile_crawler.client.token,- # })-return Cascade