Skip to content

Bulk asynchronous downloader for multiple file hosts

Change everything to url yarl.URLs.

Jules-WinnfieldX43b462956f7e
diff --git a/cyberdrop_dl/__init__.py b/cyberdrop_dl/__init__.py
index 6c96c9755..21e33ba2c 100644
--- a/cyberdrop_dl/__init__.py
+++ b/cyberdrop_dl/__init__.py
@@ -1 +1 @@
-__version__ = "2.10.2"
+__version__ = "2.10.3"
diff --git a/cyberdrop_dl/main.py b/cyberdrop_dl/main.py
index cb7f59756..b1f92f6c1 100644
--- a/cyberdrop_dl/main.py
+++ b/cyberdrop_dl/main.py
@@ -2,6 +2,8 @@ import argparse
import asyncio
from pathlib import Path
+import yarl
+
from . import __version__ as VERSION
from .utils.scraper import scrape
from .utils.downloaders import get_downloaders
@@ -25,7 +27,10 @@ def parse_args():
def regex_links(urls) -> list:
all_links = [x.group().replace(".md.", ".") for x in re.finditer(r"(?:http.*?)(?=('|$|\n|\r\n|\r|\s|\"|\[/URL]))", urls)]
- return all_links
+ yarl_links = []
+ for link in all_links:
+ yarl_links.append(yarl.URL(link))
+ return yarl_links
async def download_all(args: argparse.Namespace):
@@ -42,8 +47,6 @@ async def download_all(args: argparse.Namespace):
with open(input_file, "r") as f:
links += regex_links(f.read())
content_object = await scrape(links, args.include_id)
- # TODO return unsupported links, instead of raising error when no links in content object, print unsupported and
- # exit
if content_object.is_empty():
logging.error(f'ValueError No links')
log('No links found, check the URL.txt\nIf the link works in your web browser, '
diff --git a/cyberdrop_dl/utils/base_functions.py b/cyberdrop_dl/utils/base_functions.py
index 6272a8d69..3c100ced1 100644
--- a/cyberdrop_dl/utils/base_functions.py
+++ b/cyberdrop_dl/utils/base_functions.py
@@ -3,6 +3,7 @@ import os
import re
from urllib.parse import urljoin
+from yarl import *
from colorama import Fore, Style
"""This file contains generic information and functions that are used around the program"""
@@ -60,33 +61,31 @@ def make_title_safe(title: str):
return title
-def bunkr_parse(url: str) -> str:
+def bunkr_parse(url: URL) -> URL:
"""Fix the URL for bunkr.is."""
- extension = '.' + url.split('.')[-1]
+ extension = '.' + str(url).split('.')[-1]
if extension.lower() in FILE_FORMATS['Videos']:
- 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_url
+ url = url.with_host('media-files.bunkr.is')
+ return url
if extension.lower() in FILE_FORMATS['Images']:
- changed_url = url.replace('i.bunkr', 'cdn.bunkr')
- return changed_url
+ url = url.with_host('cdn.bunkr.is')
+ return url
return url
-def pixeldrain_parse(url: str, title: str) -> str:
+def pixeldrain_parse(url: URL, title: str) -> URL:
"""Fix the URL for Pixeldrain"""
- if url.split('/')[-2] == 'l':
- final_url = f'https://pixeldrain.com/api/list/{title}/zip'
+ if url.parts[1] == 'l':
+ final_url = URL('https://pixeldrain.com/api/list/') / title / 'zip'
else:
- final_url = f"https://pixeldrain.com/api/file/{title}?download"
+ final_url = (URL('https://pixeldrain.com/api/file/') / title).with_query('download')
return final_url
-def check_direct(url: str):
+def check_direct(url: URL):
mapping_direct = ['i.pixl.is', r's..putmega.com', r's..putme.ga', r'img-...cyberdrop...', r'f.cyberdrop...',
r'fs-...cyberdrop...', r'cdn.bunkr...', r'media-files.bunkr...', r'jpg.church/images/...']
for domain in mapping_direct:
- if re.search(domain, url):
+ if re.search(domain, url.host):
return True
return False
diff --git a/cyberdrop_dl/utils/crawlers/Chibisafe_Spider.py b/cyberdrop_dl/utils/crawlers/Chibisafe_Spider.py
index f600bddee..f7e6cc8ea 100644
--- a/cyberdrop_dl/utils/crawlers/Chibisafe_Spider.py
+++ b/cyberdrop_dl/utils/crawlers/Chibisafe_Spider.py
@@ -10,13 +10,13 @@ class ChibisafeCrawler():
self.include_id = include_id
async def fetch(self, session, url):
- url_extract = tldextract.extract(url)
+ url_extract = tldextract.extract(str(url))
base_domain = "{}.{}".format(url_extract.domain, url_extract.suffix)
domain_obj = DomainItem(base_domain, {})
cookies = []
- log("Starting scrape of " + url, Fore.WHITE)
- logging.debug("Starting scrape of " + url)
+ log("Starting scrape of " + str(url), Fore.WHITE)
+ logging.debug("Starting scrape of " + str(url))
try:
async with session.get(url) as response:
@@ -25,25 +25,25 @@ class ChibisafeCrawler():
title = soup.select_one("h1[id=title]").get_text()
if title is None:
- title = response.url.split('/')[-1]
+ title = url.name
elif self.include_id:
- titlep2 = response.url.split('/')
+ titlep2 = url.name
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')
- if 'bunkr' in link:
+ link = URL(link.get('href'))
+ if 'bunkr' in link.host:
link = bunkr_parse(link)
domain_obj.add_to_album(title, link, url)
except Exception as e:
- logger.debug("Error encountered while handling %s", url, exc_info=True)
+ logger.debug("Error encountered while handling %s", str(url), exc_info=True)
logger.debug(e)
- log("Finished scrape of " + url, Fore.WHITE)
- logging.debug("Finished scrape of " + url)
+ log("Finished scrape of " + str(url), Fore.WHITE)
+ logging.debug("Finished scrape of " + str(url))
return domain_obj, cookies
diff --git a/cyberdrop_dl/utils/crawlers/Erome_Spider.py b/cyberdrop_dl/utils/crawlers/Erome_Spider.py
index 8666ca709..4d6f93557 100644
--- a/cyberdrop_dl/utils/crawlers/Erome_Spider.py
+++ b/cyberdrop_dl/utils/crawlers/Erome_Spider.py
@@ -10,13 +10,13 @@ class EromeCrawler():
self.include_id = include_id
async def fetch(self, session, url):
- url_extract = tldextract.extract(url)
+ url_extract = tldextract.extract(str(url))
base_domain = "{}.{}".format(url_extract.domain, url_extract.suffix)
domain_obj = DomainItem(base_domain, {})
cookies = []
- log("Starting scrape of " + url, Fore.WHITE)
- logging.debug("Starting scrape of " + url)
+ log("Starting scrape of " + str(url), Fore.WHITE)
+ logging.debug("Starting scrape of " + str(url))
try:
async with session.get(url) as response:
@@ -26,24 +26,24 @@ class EromeCrawler():
# Title
title = soup.select_one('div[class="col-sm-12 page-content"] h1').get_text()
if title is None:
- title = response.url.split('/')[-1]
+ title = url.name
elif self.include_id:
- title = title + " - " + url.split('/')[-1]
+ title = title + " - " + url.name
title = make_title_safe(title)
# Images
for link in soup.select('img[class="img-front lasyload"]'):
- domain_obj.add_to_album(title, link['data-src'], url)
+ 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'):
- domain_obj.add_to_album(title, link['src'], url)
+ domain_obj.add_to_album(title, URL(link['src']), url)
except Exception as e:
- logger.debug("Error encountered while handling %s", url, exc_info=True)
+ logger.debug("Error encountered while handling %s", str(url), exc_info=True)
logger.debug(e)
- log("Finished scrape of " + url, Fore.WHITE)
- logging.debug("Finished scrape of " + url)
+ log("Finished scrape of " + str(url), Fore.WHITE)
+ logging.debug("Finished scrape of " + str(url))
return domain_obj, cookies
diff --git a/cyberdrop_dl/utils/crawlers/GoFile_Spider.py b/cyberdrop_dl/utils/crawlers/GoFile_Spider.py
index 4d0795c89..b0bfecb91 100644
--- a/cyberdrop_dl/utils/crawlers/GoFile_Spider.py
+++ b/cyberdrop_dl/utils/crawlers/GoFile_Spider.py
@@ -28,7 +28,7 @@ class GofileCrawler():
async def get_links(self, url, og_title=None):
results = []
- content_id = url.split("/")[-1] if url.startswith("https://gofile.io/") else url
+ content_id = url.name if url.host == 'gofile.io' else url
content = self.client.get_content(content_id)
if not content:
return
@@ -40,8 +40,8 @@ class GofileCrawler():
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))
+ results.extend(result for result in await self.get_links(URL(val["code"]), title))
else:
- results.append({'url': val["link"] if val["link"] != "overloaded" else val["directLink"],
- 'title': title, 'referral': 'https://gofile.io/'})
+ results.append({'url': URL(val["link"]) if val["link"] != "overloaded" else URL(val["directLink"]),
+ 'title': title, 'referral': URL('https://gofile.io/')})
return results
diff --git a/cyberdrop_dl/utils/crawlers/ShareX_Spider.py b/cyberdrop_dl/utils/crawlers/ShareX_Spider.py
index 23e9b4cf5..d8f319025 100644
--- a/cyberdrop_dl/utils/crawlers/ShareX_Spider.py
+++ b/cyberdrop_dl/utils/crawlers/ShareX_Spider.py
@@ -10,27 +10,27 @@ class ShareXCrawler():
self.include_id = include_id
async def fetch(self, session, url):
- url_extract = tldextract.extract(url)
+ url_extract = tldextract.extract(str(url))
base_domain = "{}.{}".format(url_extract.domain, url_extract.suffix)
domain_obj = DomainItem(base_domain, {})
cookies = []
- log("Starting scrape of " + url, Fore.WHITE)
- logging.debug("Starting scrape of " + url)
+ log("Starting scrape of " + str(url), Fore.WHITE)
+ logging.debug("Starting scrape of " + str(url))
- if "/album/" in url or "/a/" in url:
+ if "album" in url.parts or "a" in url.parts:
results = await self.parse(url, session)
- elif "/albums" in url:
+ elif "albums" in url.parts:
results = await self.get_albums(url, session)
- elif '/image/' in url or '/img/' in url or '/images/' in url:
+ elif 'image' in url.parts or 'img' in url.parts or 'images' in url.parts:
results = await self.get_singular(url, session)
else:
results = await self.parse_profile(url, session)
for result in results:
domain_obj.add_to_album(result['title'], result['url'], result['referral'])
- log("Finished scrape of " + url, Fore.WHITE)
- logging.debug("Finished scrape of " + url)
+ log("Finished scrape of " + str(url), Fore.WHITE)
+ logging.debug("Finished scrape of " + str(url))
return domain_obj, cookies
@@ -42,10 +42,10 @@ class ShareXCrawler():
soup = BeautifulSoup(text, 'html.parser')
albums = soup.select("a[class='image-container --media']")
for album in albums:
- album_url = album.get('href')
+ album_url = URL(album.get('href'))
results.extend(result for result in await self.parse(album_url, session))
except Exception as e:
- logger.debug("Error encountered while handling %s", url, exc_info=True)
+ logger.debug("Error encountered while handling %s", str(url), exc_info=True)
logger.debug(e)
return results
@@ -55,12 +55,12 @@ class ShareXCrawler():
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.', '.')
+ 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", url, exc_info=True)
+ logger.debug("Error encountered while handling %s", str(url), exc_info=True)
logger.debug(e)
return results
@@ -74,9 +74,10 @@ class ShareXCrawler():
for album in albums:
album_url = album.get('data-url-short')
if album_url is not None:
+ album_url = URL(album_url)
results.extend(result for result in await self.parse(album_url, session, og_title=og_title))
except Exception as e:
- logger.debug("Error encountered while handling %s", url, exc_info=True)
+ logger.debug("Error encountered while handling %s", str(url), exc_info=True)
logger.debug(e)
return results
@@ -88,18 +89,16 @@ class ShareXCrawler():
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]
+ title = url.name
elif self.include_id:
- titlep2 = response.url.split('/')
- titlep2 = [s for s in titlep2 if "." in s][-1]
+ titlep2 = url.name
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')
+ list_recent = URL(soup.select_one("a[id=list-most-recent-link]").get('href'))
results.extend(result for result in await self.get_list_links(list_recent, session, title))
except Exception as e:
- logger.debug("Error encountered while handling %s", url, exc_info=True)
+ logger.debug("Error encountered while handling %s", str(url), exc_info=True)
logger.debug(e)
return results
@@ -109,21 +108,22 @@ class ShareXCrawler():
async with session.get(url) as response:
text = await response.text()
soup = BeautifulSoup(text, 'html.parser')
- if 'jpg.church' in 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 = link.get('src')
- link = link.replace('.md.', '.').replace('.th.', '.')
+ link = URL(link.get('src'))
+ link = link.with_name(link.name.replace('.md.', '.').replace('.th.', '.'))
results.append({'url': link, 'title': title, 'referral': url, 'cookies': ''})
next_page = soup.select_one('li.pagination-next a')
if next_page is not None:
next_page = next_page.get('href')
if next_page is not None:
+ next_page = URL(next_page)
results.extend(result for result in await self.get_list_links(next_page, session, title))
except Exception as e:
- logger.debug("Error encountered while handling %s", url, exc_info=True)
+ logger.debug("Error encountered while handling %s", str(url), exc_info=True)
logger.debug(e)
return results
@@ -136,23 +136,22 @@ class ShareXCrawler():
title = soup.select_one("a[data-text=album-name]").get_text()
if title is None:
- title = response.url.split('/')[-1]
+ title = url.name
elif self.include_id:
- titlep2 = response.url.split('/')
- titlep2 = [s for s in titlep2 if "." in s][-1]
+ titlep2 = url.name
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")
+ sub_albums = URL(soup.select_one("a[id=tab-sub-link]").get("href"))
results.extend(result for result in await self.get_sub_album_links(sub_albums, session, title))
- list_recent = soup.select_one("a[id=list-most-recent-link]").get("href")
+ list_recent = URL(soup.select_one("a[id=list-most-recent-link]").get("href"))
results.extend(result for result in await self.get_list_links(list_recent, session, title))
except Exception as e:
- logger.debug("Error encountered while handling %s", url, exc_info=True)
+ logger.debug("Error encountered while handling %s", str(url), exc_info=True)
logger.debug(e)
return results
\ No newline at end of file
diff --git a/cyberdrop_dl/utils/data_classes.py b/cyberdrop_dl/utils/data_classes.py
index f27e9ba17..bf9d47e8a 100644
--- a/cyberdrop_dl/utils/data_classes.py
+++ b/cyberdrop_dl/utils/data_classes.py
@@ -1,6 +1,8 @@
from dataclasses import dataclass
from typing import Optional, List, Dict, Tuple, AnyStr, Any
+from yarl import *
+
@dataclass
class CookiesItem:
@@ -36,7 +38,7 @@ class DomainItem:
domain: str
albums: Dict[str, AlbumItem]
- def add_to_album(self, title: str, link: str, referral: str):
+ def add_to_album(self, title: str, link: URL, referral: URL):
if title in self.albums.keys():
self.albums[title].add_link_pair(link, referral)
else:
@@ -64,7 +66,7 @@ class CascadeItem:
for title, album in albums.items():
self.add_album(domain, title, album)
- def add_to_album(self, domain: str, title: str, link: str, referral: str):
+ def add_to_album(self, domain: str, title: str, link: URL, referral: URL):
if domain in self.domains.keys():
self.domains[domain].add_to_album(title, link, referral)
else:
diff --git a/cyberdrop_dl/utils/downloaders.py b/cyberdrop_dl/utils/downloaders.py
index 90eb38122..b6517aa8d 100644
--- a/cyberdrop_dl/utils/downloaders.py
+++ b/cyberdrop_dl/utils/downloaders.py
@@ -13,7 +13,6 @@ import aiohttp
import aiohttp.client_exceptions
import certifi
from tqdm import tqdm
-import yarl
from .base_functions import *
from .data_classes import *
@@ -38,7 +37,7 @@ def retry(f):
return wrapper
-async def throttle(self, url: yarl.URL) -> None:
+async def throttle(self, url: URL) -> None:
host = url.host
if host is None:
return
@@ -82,20 +81,20 @@ class Downloader:
@retry
async def download_file(
self,
- url: str,
- referral: str,
+ url: URL,
+ referral: URL,
filename: str,
session: aiohttp.ClientSession,
show_progress: bool = True
) -> None:
"""Download the content of given URL"""
- headers = {'Referer': referral, 'user-agent': user_agent}
+ headers = {'Referer': str(referral), 'user-agent': user_agent}
ssl_context = ssl.create_default_context(cafile=certifi.where())
try:
async with self._semaphore:
- if yarl.URL(url).host in self.delay:
- await throttle(self, yarl.URL(url))
+ if url.host in self.delay:
+ await throttle(self, url)
ext = '.'+filename.split('.')[-1]
if not (ext in FILE_FORMATS['Images'] or ext in FILE_FORMATS['Videos'] or ext in FILE_FORMATS['Audio'] or ext in FILE_FORMATS['Other']):
@@ -156,9 +155,9 @@ class Downloader:
"""Download the content of given URL and store it in a file."""
url, referral = url_tuple
- filename = url.split("/")[-1]
+ filename = url.name
filename = sanitize(filename)
- if "?v=" in url:
+ if "v=" in filename:
filename = filename.split('v=')[0]
if len(filename) > MAX_FILENAME_LENGTH:
fileext = filename.split('.')[-1]
@@ -167,7 +166,7 @@ class Downloader:
if (self.folder / self.title / filename).exists():
logger.debug(str(self.folder / self.title / filename) + " Already Exists")
else:
- logger.debug("Working on " + url)
+ logger.debug("Working on " + str(url))
try:
await self.download_file(url, referral=referral, filename=filename,
session=session, show_progress=show_progress)
diff --git a/cyberdrop_dl/utils/scraper.py b/cyberdrop_dl/utils/scraper.py
index 7ea559241..6ca342d3f 100644
--- a/cyberdrop_dl/utils/scraper.py
+++ b/cyberdrop_dl/utils/scraper.py
@@ -18,13 +18,11 @@ async def scrape(urls, include_id: bool):
Chibisafe_urls = []
Erome_urls = []
GoFile_urls = []
- unsupported_urls = []
log("Starting Scrape", Fore.WHITE)
for url in urls:
- url = url.replace('\n', '')
- url_extract = tldextract.extract(url)
+ url_extract = tldextract.extract(str(url))
base_domain = "{}.{}".format(url_extract.domain, url_extract.suffix)
if base_domain in mapping_ShareX:
@@ -49,13 +47,13 @@ async def scrape(urls, include_id: bool):
GoFile_urls.append(url)
elif base_domain in mapping_Pixeldrain:
- title = url.split('/')[-1]
+ title = str(url).split('/')[-1]
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)
+ log(str(url) + " is not supported currently.")
erome_crawler = EromeCrawler(include_id=include_id)
sharex_crawler = ShareXCrawler(include_id=include_id)