Skip to content

Bulk asynchronous downloader for multiple file hosts

This isn't perfect, but it's a rough implementation of GoFile downloading.

Julesb40dbb497065
diff --git a/main.py b/main.py
index ef12d31b2..c263778cd 100644
--- a/main.py
+++ b/main.py
@@ -17,7 +17,7 @@ logging.basicConfig(level=logging.DEBUG, filename='logs.log',
filemode='w')
warnings.filterwarnings("ignore", category=DeprecationWarning)
-SUPPORTED_URLS = {'cyberdrop.me', 'bunkr.is', "bunkr.to", 'pixl.is', 'putme.ga', 'putmega.com'}
+SUPPORTED_URLS = {'cyberdrop.me', 'bunkr.is', "bunkr.to", 'pixl.is', 'putme.ga', 'putmega.com', 'gofile.io'}
CPU_COUNT = settings.threads if settings.threads != 0 else multiprocessing.cpu_count()
DOWNLOAD_FOLDER = settings.download_folder
@@ -36,7 +36,7 @@ def clear():
def version_check() -> None:
response = requests.get("https://api.github.com/repos/Jules-WinnfieldX/CyberDropDownloader/releases/latest")
latest_version = response.json()["tag_name"]
- current_version = "2.1.7"
+ current_version = "2.1.8"
logging.debug(f"We are running version {current_version} of Cyberdrop Downloader")
if latest_version != current_version:
log("A new version of CyberDropDownloader is available\n"
@@ -57,12 +57,12 @@ async def main():
file_object = open("URLs.txt", "r")
urls = [line for line in file_object]
- content_object = scrape(urls)
+ cookies, content_object = scrape(urls)
if not content_object:
logging.error(f'ValueError No links: {content_object}')
raise ValueError('No links found, check the URL.txt\nNote: This utility only supports album links, not direct links to pictures or videos.')
- downloaders = get_downloaders(content_object, folder=Path(DOWNLOAD_FOLDER), max_workers=CPU_COUNT)
+ downloaders = get_downloaders(content_object, cookies=cookies, folder=Path(DOWNLOAD_FOLDER), max_workers=CPU_COUNT)
for downloader in downloaders:
await downloader.download_content()
diff --git a/requirements.txt b/requirements.txt
index d3c60a780..dfee28d93 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -8,3 +8,5 @@ tqdm~=4.62.3
sanitize-filename~=1.2.0
readchar~=3.0.4
certifi~=2021.10.8
+selenium~=4.1.0
+chromedriver_autoinstaller~=0.3.1
\ No newline at end of file
diff --git a/utils/downloaders.py b/utils/downloaders.py
index 10975d93a..cf46edec5 100644
--- a/utils/downloaders.py
+++ b/utils/downloaders.py
@@ -1,4 +1,5 @@
import asyncio
+import http
import itertools
from functools import wraps
from pathlib import Path
@@ -13,6 +14,7 @@ import logging
from sanitize_filename import sanitize
import ssl
import certifi
+from http.cookies import SimpleCookie
logger = logging.getLogger(__name__)
@@ -47,7 +49,7 @@ class FailureException(Exception):
def retry(
attempts: int,
timeout: Union[int, float] = 0,
- exceptions: Iterable[Type[Exception]] = (Exception,)
+ exceptions: Type[Exception] = Exception
) -> Callable:
def inner(func: T_Func) -> T_Func:
@wraps(func)
@@ -70,8 +72,9 @@ def retry(
class Downloader:
- def __init__(self, links: List[str], folder: Path, title: str, max_workers: int):
+ def __init__(self, links: List[List[str]], morsels, folder: Path, title: str, max_workers: int):
self.links = links
+ self.morsels = morsels
self.folder = folder
self.title = title
self.max_workers = max_workers
@@ -82,6 +85,7 @@ class Downloader:
async def download_file(
self,
url: str,
+ referal: str,
filename: str,
session: aiohttp.ClientSession,
headers: Optional[CaseInsensitiveDict] = None,
@@ -92,13 +96,14 @@ class Downloader:
resume_point = 0
downloaded = bytearray()
ssl_context = ssl.create_default_context(cafile=certifi.where())
+ user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36'
+
+ headers = {'Referer': referal, 'user-agent': user_agent}
if temp_file.exists():
resume_point = temp_file.stat().st_size
- if headers:
- headers['Range'] = 'bytes=%d-' % resume_point
- else:
- headers = {'Range': 'bytes=%d-' % resume_point}
+ headers['Range'] = 'bytes=%d-' % resume_point
+
try:
async with self._semaphore:
resp = await session.get(url, headers=headers, ssl=ssl_context)
@@ -133,23 +138,26 @@ class Downloader:
async def download_and_store(
self,
- url: str,
+ url_object: list,
session: aiohttp.ClientSession,
headers: Optional[CaseInsensitiveDict] = None,
show_progress: bool = True
) -> None:
"""Download the content of given URL and store it in a file."""
+ url = url_object[0]
+ referal = url_object[1]
+
filename = sanitize(url.split("/")[-1])
if (self.folder / self.title / filename).exists():
logger.debug(str(self.folder / self.title / filename) + " Already Exists")
else:
logger.debug("Working on " + url)
- await self.download_file(url, filename=filename, session=session, headers=headers, show_progress=show_progress)
+ await self.download_file(url, referal=referal, filename=filename, session=session, headers=headers, show_progress=show_progress)
await self.rename_file(filename)
async def download_all(
self,
- links: Iterable[str],
+ links: Iterable[List[str]],
session: aiohttp.ClientSession,
headers: Optional[CaseInsensitiveDict] = None,
show_progress: bool = True
@@ -168,10 +176,11 @@ class Downloader:
"""Download the content of all links and save them as files."""
(self.folder / self.title).mkdir(parents=True, exist_ok=True)
async with aiohttp.ClientSession() as session:
+ session.cookie_jar.update_cookies(self.morsels)
await self.download_all(self.links, session, headers=headers, show_progress=show_progress)
-class BunkrDownloader(Downloader):
+class LimitDownloader(Downloader):
@staticmethod
def bunkr_parse(url: str) -> str:
"""Fix the URL for bunkr.is and construct the headers."""
@@ -187,7 +196,7 @@ class BunkrDownloader(Downloader):
return url
@staticmethod
- def pairwise_skipping(it: Iterable[T], chunk_size: int) -> Tuple[T, ...]:
+ def pairwise_skipping(it: List[T], chunk_size: int):
"""Iterate over tuples of the iterable of size `chunk_size` at a time."""
split_it = [it[i:i+chunk_size] for i in range(0, len(it), chunk_size)]
return map(tuple, split_it)
@@ -195,17 +204,19 @@ class BunkrDownloader(Downloader):
async def download_file(
self,
url: str,
+ referal: str,
filename: str,
session: aiohttp.ClientSession,
headers: Optional[CaseInsensitiveDict] = None,
show_progress: bool = True
- ) -> bytearray:
- url = self.bunkr_parse(url)
- return await super().download_file(url, filename=filename, session=session, headers=headers, show_progress=show_progress)
+ ):
+ if 'bunkr' in url:
+ url = self.bunkr_parse(url)
+ await super().download_file(url, referal=referal, filename=filename, session=session, headers=headers, show_progress=show_progress)
async def download_all(
self,
- links: Iterable[str],
+ links: Iterable[List[str]],
session: aiohttp.ClientSession,
headers: Optional[CaseInsensitiveDict] = None,
show_progress: bool = True
@@ -220,7 +231,22 @@ class BunkrDownloader(Downloader):
await super().download_all(links, session, headers=headers, show_progress=show_progress)
-def get_downloaders(urls: Dict[str, Dict[str, List[str]]], folder: Path, max_workers: int) -> List[Downloader]:
+def simple_cookies(cookies: Iterable[str]):
+ morsels = {}
+ for cookie in cookies:
+ # https://docs.python.org/3/library/http.cookies.html#morsel-objects
+ morsel = http.cookies.Morsel()
+ morsel.set(cookie["name"], cookie["value"], cookie["value"])
+ morsel["domain"] = cookie["domain"]
+ morsel["httponly"] = cookie["httpOnly"]
+ morsel["path"] = cookie["path"]
+ morsel["secure"] = cookie["secure"]
+
+ morsels[cookie["name"]] = morsel
+ return morsels
+
+
+def get_downloaders(urls: Dict[str, Dict[str, List[str]]], cookies: Iterable[str], folder: Path, max_workers: int) -> List[Downloader]:
"""Get a list of downloaders for each supported type of URLs.
We shouldn't just assume that each URL will have the same netloc as
@@ -230,19 +256,22 @@ def get_downloaders(urls: Dict[str, Dict[str, List[str]]], folder: Path, max_wor
"""
mapping = {
'cyberdrop.me': Downloader,
- 'bunkr.is': BunkrDownloader,
+ 'bunkr.is': LimitDownloader,
'pixl.is': Downloader,
'putme.ga': Downloader,
'putmega.com': Downloader,
- 'cyberdrop.to': Downloader
+ 'cyberdrop.to': Downloader,
+ 'gofile.io': Downloader
}
downloaders = []
+ morsels = simple_cookies(cookies)
+
for domain, url_object in urls.items():
if domain not in mapping:
logging.error('Invalid URL!')
raise ValueError('Invalid URL!')
for title, urls in url_object.items():
- downloader = mapping[domain](urls, title=title, folder=folder, max_workers=max_workers)
+ downloader = mapping[domain](urls, morsels=morsels, title=title, folder=folder, max_workers=max_workers)
downloaders.append(downloader)
return downloaders
diff --git a/utils/scrapers.py b/utils/scrapers.py
index 2f00e3cbe..13f7545b3 100644
--- a/utils/scrapers.py
+++ b/utils/scrapers.py
@@ -4,6 +4,11 @@ from scrapy.utils.project import get_project_settings
from scrapy.http.request import Request
from scrapy.signalmanager import dispatcher
from urllib.parse import urlparse
+import chromedriver_autoinstaller
+from selenium import webdriver
+from selenium.webdriver.common.by import By
+from selenium.webdriver.support import expected_conditions as EC
+from selenium.webdriver.support.wait import WebDriverWait
import logging
import re
@@ -19,7 +24,7 @@ class ShareXSpider(Spider):
for url in self.myurls:
yield Request(url, self.parse)
- def parse(self, response):
+ def parse(self, response, **kwargs):
list_recent = response.css('a[id=list-most-recent-link]::attr(href)').get()
title = response.css('a[data-text=album-name]::text').get()
title = title.replace(r"\n", "").strip()
@@ -37,7 +42,7 @@ class ShareXSpider(Spider):
else:
for link in links:
netloc = urlparse(link).netloc.replace('www.', '')
- yield {'netloc': netloc, 'url': link.replace('.md.', '.').replace('.th.', '.'), 'title': title}
+ yield {'netloc': netloc, 'url': link.replace('.md.', '.').replace('.th.', '.'), 'title': title, 'referal': response.url, 'cookies': ''}
class ChibisafeSpider(Spider):
@@ -51,13 +56,41 @@ class ChibisafeSpider(Spider):
for url in self.myurls:
yield Request(url, self.parse)
- def parse(self, response):
+ def parse(self, response, **kwargs):
links = response.css('a[class=image]::attr(href)').getall()
title = response.css('h1[id=title]::text').get()
title = title.replace(r"\n", "").strip()
for link in links:
netloc = urlparse(link).netloc.replace('www.', '')
- yield {'netloc': netloc, 'url': link, 'title': title}
+ yield {'netloc': netloc, 'url': link, 'title': title, 'referal': response.url, 'cookies': ''}
+
+
+class GoFileSpider(Spider):
+ name = 'GoFile'
+
+ def __init__(self, *args, **kwargs):
+ self.myurls = kwargs.get('myurls', [])
+ chromedriver_autoinstaller.install()
+ self.driver = webdriver.Chrome()
+ super(GoFileSpider, self).__init__(*args, **kwargs)
+
+ def start_requests(self):
+ for url in self.myurls:
+ yield Request(url, self.parse)
+
+ def parse(self, response, **kwargs):
+ self.driver.get(response.url)
+ element = WebDriverWait(self.driver, 10).until(
+ EC.presence_of_element_located((By.ID, 'contentId-download'))
+ )
+ cookies = self.driver.get_cookies()
+ links = self.driver.find_elements(By.XPATH, "//button[@id='contentId-download']/..")
+ title = self.driver.find_element(By.ID, 'rowFolder-folderName').text
+ for link in links:
+ link = link.get_attribute("href")
+ netloc = urlparse(link).netloc.replace('www.', '')
+ yield {'netloc': netloc, 'url': link, 'title': title, 'referal': response.url, 'cookies': cookies}
+ self.driver.close()
def sanitize_key(key):
@@ -71,17 +104,23 @@ def sanitize_key(key):
key = "putme.ga"
elif "putmega" in key:
key = 'putme.ga'
+ elif "gofile" in key:
+ key = 'gofile.io'
return key
def scrape(urls):
mapping_ShareX = ["pixl.is", "putme.ga", "putmega.com"]
mapping_Chibisafe = ["cyberdrop.me", "bunkr.is", "bunkr.to"]
+ mapping_GoFile = ["gofile.io"]
ShareX_urls = []
Chibisafe_urls = []
+ GoFile_urls = []
unsupported_urls = []
+
+ cookies = []
result_links = {}
for url in urls:
@@ -90,13 +129,18 @@ def scrape(urls):
ShareX_urls.append(url)
elif base_domain in mapping_Chibisafe:
Chibisafe_urls.append(url)
+ elif base_domain in mapping_GoFile:
+ GoFile_urls.append(url)
else:
unsupported_urls.append(url)
def crawler_results(signal, sender, item, response, spider):
domain = sanitize_key(item['netloc'])
title = re.sub(r'[\\/*?:"<>|.]', "-", item['title'])
- result_links.setdefault(domain, {}).setdefault(title, []).append(item['url'])
+ referal = item['referal']
+ url = item['url']
+ cookies.extend(x for x in item['cookies'] if x not in cookies)
+ result_links.setdefault(domain, {}).setdefault(title, []).append([url, referal])
dispatcher.connect(crawler_results, signal=signals.item_scraped)
settings = get_project_settings()
@@ -104,5 +148,7 @@ def scrape(urls):
process = CrawlerProcess(settings)
if Chibisafe_urls: process.crawl(ChibisafeSpider, myurls=Chibisafe_urls)
if ShareX_urls: process.crawl(ShareXSpider, myurls=ShareX_urls)
+ if GoFile_urls: process.crawl(GoFileSpider, myurls=GoFile_urls)
process.start()
- return result_links
+
+ return cookies, result_links