Skip to content

Bulk asynchronous downloader for multiple file hosts

Fix my mistakes. My many many mistakes.

Jules-WinnfieldX4da46813d916
diff --git a/Start.bat b/Start.bat
index acc755b4b..e2932d009 100644
--- a/Start.bat
+++ b/Start.bat
@@ -1,4 +1,4 @@
py -m pip install -r requirements.txt --user
pause
-py ./cyberdrop-dl/main.py
+py ./cyberdrop_dl/main.py
pause
\ No newline at end of file
diff --git a/Start.sh b/Start.sh
index 293e23df8..9c99d61e4 100644
--- a/Start.sh
+++ b/Start.sh
@@ -1,4 +1,4 @@
#!/bin/sh
cd "$(dirname "$0")"
pip3 install -r requirements.txt --user
-python3 ./cyberdrop-dl/main.py
+python3 ./cyberdrop_dl/main.py
diff --git a/cyberdrop-dl/main.py b/cyberdrop-dl/main.py
deleted file mode 100644
index 2b8845590..000000000
--- a/cyberdrop-dl/main.py
+++ /dev/null
@@ -1,90 +0,0 @@
-import asyncio
-import logging
-import os
-from pathlib import Path
-import re
-import warnings
-
-from colorama import Fore, Style
-import nest_asyncio
-import readchar
-import requests
-
-import settings
-from utils.scraper import scrape
-from utils.downloaders import get_downloaders
-
-
-# Fixes reactor already installed error (issue using Scrapy with Asyncio)
-try:
- asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
-except Exception:
- pass
-
-logging.basicConfig(level=logging.DEBUG, filename='../logs.log',
- format='%(asctime)s:%(levelname)s:%(module)s:%(filename)s:%(lineno)d:%(message)s',
- filemode='w')
-warnings.filterwarnings("ignore", category=DeprecationWarning)
-
-DOWNLOAD_FOLDER = settings.download_folder
-
-
-def log(text, style):
- # Log function for printing to command line
- print(style + str(text) + Style.RESET_ALL)
-
-
-def clear():
- # Clears command window
- os.system('cls' if os.name == 'nt' else '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.6.1"
- 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"
- "Download it here: https://github.com/Jules-WinnfieldX/CyberDropDownloader/releases/latest\n", Fore.RED)
- input("To continue anyways press enter")
- clear()
-
-
-def regex_links(urls) -> list:
- all_links = [x.group().replace(".md.", ".") for x in re.finditer(r"(?:http.*?)(?=('|$|\n|\r\n|\r|\s)|\")", urls)]
- return all_links
-
-
-async def main():
- nest_asyncio.apply()
- clear()
- version_check()
- if os.path.isfile("../URLs.txt"):
- log("URLs.txt exists", Fore.WHITE)
- else:
- f = open("../URLs.txt", "w+")
- log("URLs.txt created", Fore.WHITE)
- exit()
-
- file_object = open("../URLs.txt", "r")
- urls = file_object.read()
- urls = regex_links(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\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(DOWNLOAD_FOLDER))
-
- for downloader in downloaders:
- await downloader.download_content()
- log('Finished scraping. Enjoy :)', Fore.WHITE)
- log('If you have ".download" files remaining, rerun this program. You most likely ran into download attempts limit',
- Fore.WHITE)
- repr(readchar.readchar())
-
-
-if __name__ == '__main__':
- asyncio.get_event_loop().run_until_complete(main())
diff --git a/cyberdrop-dl/settings.py b/cyberdrop-dl/settings.py
deleted file mode 100644
index feabc903e..000000000
--- a/cyberdrop-dl/settings.py
+++ /dev/null
@@ -1,11 +0,0 @@
-# Change at own risk, values here are default
-# Defaults:
-# threads = 0 - (Will run all threads), **this is not the same as cores.**
-# download_folder = "./Downloads/" - will download in the CyberDropDownloader folder
-# download_attempts = 10 - will try and download each file 10 times before giving up.
-# include_id_in_download_folder_name = False - setting this to true will add the ID to download folder names.
-
-threads = 0
-download_folder = "./Downloads/"
-download_attempts = 10
-include_id_in_download_folder_name = False
diff --git a/cyberdrop-dl/utils/crawlers/Chibisafe_Spider.py b/cyberdrop-dl/utils/crawlers/Chibisafe_Spider.py
deleted file mode 100644
index 83a662821..000000000
--- a/cyberdrop-dl/utils/crawlers/Chibisafe_Spider.py
+++ /dev/null
@@ -1,84 +0,0 @@
-import re
-from urllib.parse import urlparse, urljoin
-
-from scrapy import Spider
-from scrapy.http.request import Request
-
-from ...settings import include_id_in_download_folder_name as title_setting
-
-
-FILE_FORMATS = {
- 'Images': {
- '.jpg', '.jpeg', '.png', '.gif',
- '.gif', '.webp', '.jpe', '.svg',
- '.tif', '.tiff', '.jif',
- },
- 'Videos': {
- '.mpeg', '.avchd', '.webm', '.mpv',
- '.swf', '.avi', '.m4p', '.wmv',
- '.mp2', '.m4v', '.qt', '.mpe',
- '.mp4', '.flv', '.mov', '.mpg',
- '.ogg',
- },
- 'Audio': {
- '.mp3', '.flac', '.wav', '.m4a'
- }
-}
-
-
-def bunkr_parse(url: str) -> str:
- """Fix the URL for bunkr.is and construct the headers."""
- extension = '.' + url.split('.')[-1]
- if extension.lower() in FILE_FORMATS['Videos']:
- changed_url = url.replace('cdn.bunkr', 'media-files.bunkr').split('/')
- changed_url = ''.join(map(lambda x: urljoin('/', x), changed_url))
- return changed_url
- if extension.lower() in FILE_FORMATS['Images']:
- changed_url = url.replace('i.bunkr', 'cdn.bunkr')
- return changed_url
- return url
-
-
-class Chibisafe_Spider(Spider):
- name = 'Chibisafe'
-
- def __init__(self, *args, **kwargs):
- self.myurls = kwargs.get('myurls', [])
- 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]})
-
- 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': ''}
-
- def parse(self, response, **kwargs):
- links = response.css('a[class=image]::attr(href)').getall()
-
- try:
- title = response.css('h1[id=title]::text').get()
- title = title.replace(r"\n", "").strip()
- if title_setting:
- title = title + " - " + response.url.split('/')[-1]
- except Exception as e:
- title = response.url.split('/')[-1]
- title = re.sub(r'[/]', "-", title)
-
- for link in links:
- netloc = urlparse(link).netloc.replace('www.', '')
- yield {'netloc': netloc, 'url': bunkr_parse(link), 'title': title, 'referal': response.url, 'cookies': ''}
diff --git a/cyberdrop-dl/utils/crawlers/Erome_Spider.py b/cyberdrop-dl/utils/crawlers/Erome_Spider.py
deleted file mode 100644
index 68a918653..000000000
--- a/cyberdrop-dl/utils/crawlers/Erome_Spider.py
+++ /dev/null
@@ -1,38 +0,0 @@
-import re
-from urllib.parse import urlparse
-
-from scrapy import Spider
-from scrapy.http.request import Request
-
-from ...settings import include_id_in_download_folder_name as title_setting
-
-
-class Erome_Spider(Spider):
- name = 'Erome'
-
- def __init__(self, *args, **kwargs):
- self.myurls = kwargs.get('myurls', [])
- super(Erome_Spider, self).__init__(*args, **kwargs)
-
- def start_requests(self):
- for url in self.myurls:
- yield Request(url, self.parse)
-
- def parse(self, response, **kwargs):
- img_links = response.css('img[class="img-front lasyload"]::attr(data-src)').getall()
- vid_links = response.css('div[class=media-group] div[class=video-lg] video source::attr(src)').getall()
-
- try:
- title = response.css('div[class="col-sm-12 page-content"] h1::text').get()
- if title_setting:
- title = title + " - " + response.url.split('/')[-1]
- except Exception as e:
- title = response.url.split('/')[-1]
- title = re.sub(r'[/]', "-", title)
-
- for link in img_links:
- netloc = urlparse(link).netloc.replace('www.', '')
- yield {'netloc': netloc, 'url': link, 'title': title, 'referal': response.url, 'cookies': ''}
- for link in vid_links:
- netloc = urlparse(link).netloc.replace('www.', '')
- yield {'netloc': netloc, 'url': link, 'title': title, 'referal': response.url, 'cookies': ''}
diff --git a/cyberdrop-dl/utils/crawlers/GoFile_Spider.py b/cyberdrop-dl/utils/crawlers/GoFile_Spider.py
deleted file mode 100644
index ef8894aa6..000000000
--- a/cyberdrop-dl/utils/crawlers/GoFile_Spider.py
+++ /dev/null
@@ -1,30 +0,0 @@
-from typing import Union
-
-from gofile import Gofile
-
-
-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
diff --git a/cyberdrop-dl/utils/crawlers/ShareX_Spider.py b/cyberdrop-dl/utils/crawlers/ShareX_Spider.py
deleted file mode 100644
index 51f921d07..000000000
--- a/cyberdrop-dl/utils/crawlers/ShareX_Spider.py
+++ /dev/null
@@ -1,101 +0,0 @@
-import re
-from urllib.parse import urlparse
-
-from scrapy import Spider
-from scrapy.http.request import Request
-
-from ...settings import include_id_in_download_folder_name as title_setting
-
-
-class ShareX_Spider(Spider):
- name = 'ShareX'
-
- def __init__(self, *args, **kwargs):
- self.myurls = kwargs.get('myurls', [])
- 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):
- try:
- title = response.css('div[class=header] h1 strong::text').get()
- title = title.replace(r"\n", "").strip()
- if title_setting:
- titlep2 = response.url.split('/')
- titlep2 = [s for s in titlep2 if "." in s][-1]
- title = title + " - " + titlep2
- except Exception as e:
- title = response.url.split('/')
- title = [s for s in title if "." in s][-1]
- title = re.sub(r'[/]', "-", title)
-
- 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_albums(self, response):
- albums = response.css("a[class='image-container --media']::attr(href)").getall()
- for url in albums:
- yield Request(url, callback=self.parse)
-
- def parse(self, response, **kwargs):
- try:
- title = response.css('a[data-text=album-name]::text').get()
- title = title.replace(r"\n", "").strip()
- if title_setting:
- titlep2 = response.url.split('/')
- titlep2 = [s for s in titlep2 if "." in s][-1]
- title = title + " - " + titlep2
- except Exception as e:
- title = response.url.split('/')
- title = [s for s in title if "." in s][-1]
- title = re.sub(r'[/]', "-", title)
-
- 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')
-
- 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': ''}
diff --git a/cyberdrop-dl/utils/downloaders.py b/cyberdrop-dl/utils/downloaders.py
deleted file mode 100644
index 62466500a..000000000
--- a/cyberdrop-dl/utils/downloaders.py
+++ /dev/null
@@ -1,279 +0,0 @@
-import asyncio
-from functools import wraps
-import http
-import logging
-import multiprocessing
-from pathlib import Path
-import ssl
-import time
-import traceback
-from typing import Any, cast, Callable, Iterable, Optional, Type, TypeVar, Union
-
-import aiofiles
-import aiofiles.os
-import aiohttp
-import aiohttp.client_exceptions
-import certifi
-from colorama import Fore, Style
-from sanitize_filename import sanitize
-from tqdm import tqdm
-import yarl
-
-from ..settings import *
-
-
-asyncio.get_event_loop()
-logger = logging.getLogger(__name__)
-
-T = TypeVar("T")
-T_Func = TypeVar("T_Func", bound=Callable)
-
-MAX_FILENAME_LENGTH = 100
-FILE_FORMATS = {
- 'Images': {
- '.jpg', '.jpeg', '.png', '.gif',
- '.gif', '.webp', '.jpe', '.svg',
- '.tif', '.tiff', '.jif',
- },
- 'Videos': {
- '.mpeg', '.avchd', '.webm', '.mpv',
- '.swf', '.avi', '.m4p', '.wmv',
- '.mp2', '.m4v', '.qt', '.mpe',
- '.mp4', '.flv', '.mov', '.mpg',
- '.ogg',
- },
- 'Audio': {
- '.mp3', '.flac', '.wav', '.m4a'
- }
-}
-
-
-def log(text, style):
- # Log function for printing to command line
- print(style + str(text) + Style.RESET_ALL)
-
-
-class FailureException(Exception):
- """Basic failure exception I can throw to force a retry."""
- pass
-
-
-def retry(
- attempts: int,
- timeout: Union[int, float] = 0,
- exceptions: Type[Exception] = Exception
-) -> Callable:
- def inner(func: T_Func) -> T_Func:
- @wraps(func)
- async def wrapper(*args, **kwargs) -> Any:
- times_tried = 1
- while True:
- try:
- return await func(*args, **kwargs)
- except exceptions as exc:
- # logger.exception(exc)
- if times_tried >= attempts:
- logger.exception(f'Raised {exc} exceeded times_tried')
- raise exc
- times_tried += 1
- await asyncio.sleep(timeout)
- return cast(T_Func, wrapper)
- return inner
-
-
-async def throttle(self, url: yarl.URL) -> None:
- host = url.host
- if host is None:
- return
- delay = self.delay.get(host)
- if delay is None:
- return
-
- key: Optional[str] = None
- while True:
- if key is None:
- key = 'throttle:{}'.format(host)
- now = time.time()
- last = self.throttle_times.get(key, 0.0)
- elapsed = now - last
-
- if elapsed >= delay:
- self.throttle_times[key] = now
- return
-
- remaining = delay - elapsed + 1
-
- log_string = '\nDelaying request to %s for %.2f seconds.' % (host, remaining)
- logger.debug(log_string)
- await asyncio.sleep(remaining)
-
-
-class Downloader:
- 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
- self._semaphore = asyncio.Semaphore(max_workers)
- self.delay = {'media-files.bunkr.is': 2}
- self.throttle_times = {}
-
- """Changed from aiohttp exceptions caught to FailureException to allow for partial downloads."""
-
- @retry(attempts=download_attempts, timeout=4, exceptions=FailureException)
- async def download_file(
- self,
- url: str,
- referral: str,
- filename: str,
- session: aiohttp.ClientSession,
- show_progress: bool = True
- ) -> None:
- """Download the content of given URL"""
- 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': 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))
-
- ext = '.'+filename.split('.')[-1]
- if not (ext in FILE_FORMATS['Images'] or ext in FILE_FORMATS['Videos'] or ext in FILE_FORMATS['Audio']):
- resp = await session.get(url, headers=headers, ssl=ssl_context, raise_for_status=True)
- filename = resp.content_disposition.filename
- del resp
- if (self.folder / self.title / filename).exists():
- return
-
- resume_point = 0
- complete_file = (self.folder / self.title / filename)
- temp_file = complete_file.with_suffix(complete_file.suffix + '.part')
-
- if temp_file.exists():
- resume_point = temp_file.stat().st_size
- headers['Range'] = 'bytes=%d-' % resume_point
-
- resp = await session.get(url, headers=headers, ssl=ssl_context, raise_for_status=True)
-
- content_type = resp.headers.get('Content-Type')
- if 'text' in content_type.lower() or 'html' in content_type.lower():
- log(f"\nServer for {url} is either down or the file no longer exists", Fore.RED)
- return
-
- total = int(resp.headers.get('Content-Length', 0)) + resume_point
- 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 f.write(chunk)
- progress.update(len(chunk))
- await self.rename_file(filename)
- except (aiohttp.client_exceptions.ClientPayloadError, aiohttp.client_exceptions.ClientOSError,
- aiohttp.client_exceptions.ServerDisconnectedError, asyncio.TimeoutError, FailureException) as e:
- raise FailureException(e)
-
- async def rename_file(self, filename: 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)
- logger.debug("Finished " + filename)
-
- async def download_and_store(
- self,
- url_object: list,
- session: aiohttp.ClientSession,
- show_progress: bool = True
- ) -> None:
- """Download the content of given URL and store it in a file."""
- url = url_object[0]
- referral = url_object[1]
-
- filename = sanitize(url.split("/")[-1])
- if "?v=" in url:
- filename = filename.split('v=')[0]
- if len(filename) > MAX_FILENAME_LENGTH:
- fileext = filename.split('.')[-1]
- filename = filename[:MAX_FILENAME_LENGTH] + '.' + fileext
-
- if (self.folder / self.title / filename).exists():
- logger.debug(str(self.folder / self.title / filename) + " Already Exists")
- else:
- logger.debug("Working on " + url)
- try:
- await self.download_file(url, referral=referral, filename=filename, session=session, show_progress=show_progress)
- except Exception:
- logger.debug(traceback.format_exc())
- log(f"\nSkipping {filename}: likely exceeded download attempts (or ran into an error)\nRe-run program "
- f"after exit to continue download.", Fore.WHITE)
-
- async def download_all(
- self,
- links: Iterable[list[str]],
- session: aiohttp.ClientSession,
- show_progress: bool = True
- ) -> None:
- """Download the data from all given links and store them into corresponding files."""
- coros = [self.download_and_store(link, session, show_progress) for link in links]
- for func in tqdm(asyncio.as_completed(coros), total=len(coros), desc=self.title, unit='FILES'):
- await func
-
- async def download_content(
- self,
- show_progress: bool = True
- ) -> None:
- """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, show_progress=show_progress)
-
-
-def simple_cookies(cookies):
- 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"])
- if "domain" in cookie:
- morsel["domain"] = cookie["domain"]
- if "httpOnly" in cookie:
- morsel["httponly"] = cookie["httpOnly"]
- if "path" in cookie:
- morsel["path"] = cookie["path"]
- if "secure" in cookie:
- 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) -> 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
- the first one, so we need to classify them one by one, sort them to
- corresponding netloc URLs and create downloaders separately for individual
- netloc URLs they support.
- """
-
- downloaders = []
- morsels = simple_cookies(cookies)
-
- for domain, url_object in urls.items():
- max_workers = threads if threads != 0 else multiprocessing.cpu_count()
- for title, urls in url_object.items():
- if 'bunkr' in domain:
- max_workers = 2 if (max_workers > 2) else max_workers
- downloader = Downloader(urls, morsels=morsels, title=title, folder=folder, max_workers=max_workers)
- downloaders.append(downloader)
- return downloaders
diff --git a/cyberdrop-dl/utils/scraper.py b/cyberdrop-dl/utils/scraper.py
deleted file mode 100644
index d221bbead..000000000
--- a/cyberdrop-dl/utils/scraper.py
+++ /dev/null
@@ -1,168 +0,0 @@
-from collections import OrderedDict
-import logging
-import re
-from urllib.parse import urlparse
-
-from colorama import Fore, Style
-from scrapy import signals
-from scrapy.crawler import CrawlerProcess
-from scrapy.signalmanager import dispatcher
-from scrapy.utils.project import get_project_settings
-
-from .crawlers.ShareX_Spider import ShareX_Spider
-from .crawlers.Erome_Spider import Erome_Spider
-from .crawlers.Chibisafe_Spider import Chibisafe_Spider
-from .crawlers.GoFile_Spider import GofileCrawler
-
-
-logger = logging.getLogger(__name__)
-
-
-FILE_FORMATS = {
- 'Images': {
- '.jpg', '.jpeg', '.png', '.gif',
- '.gif', '.webp', '.jpe', '.svg',
- '.tif', '.tiff', '.jif',
- },
- 'Videos': {
- '.mpeg', '.avchd', '.webm', '.mpv',
- '.swf', '.avi', '.m4p', '.wmv',
- '.mp2', '.m4v', '.qt', '.mpe',
- '.mp4', '.flv', '.mov', '.mpg',
- '.ogg',
- },
- 'Audio': {
- '.mp3', '.flac', '.wav', '.m4a'
- }
-}
-
-
-def log(text, style):
- # Log function for printing to command line
- print(style + str(text) + Style.RESET_ALL)
-
-
-def sanitize_key(key):
- if "bunkr" in key:
- key = "bunkr.is"
- elif "pixl" in key:
- key = "pixl.is"
- elif "cyberdrop" in key:
- key = "cyberdrop.to"
- elif "putme.ga" in key:
- key = "putme.ga"
- elif "putmega" in key:
- key = 'putme.ga'
- elif "gofile" in key:
- key = "gofile.io"
- elif "church" in key:
- key = "jpg.church"
- elif "erome" in key:
- key = "erome.com"
- return key
-
-
-def check_direct(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):
- return True
- return False
-
-
-def scrape(urls):
- mapping_ShareX = ["pixl.is", "putme.ga", "putmega.com", "jpg.church"]
- mapping_Chibisafe = ["cyberdrop.me", "cyberdrop.cc", "cyberdrop.to", "cyberdrop.nl", "bunkr.is", "bunkr.to"]
- mapping_Erome = ["erome.com"]
- mapping_GoFile = ["gofile.io"]
- mapping_Pixeldrain = ["pixeldrain.com"]
-
- replacements = [
- ('fs-...', ''),
- ('f\.', ''),
- ('img-...', ''),
- ('i\.', ''),
- ('stream\.', ''),
- ('media-files', ''),
- ('www\.', ''),
- ('cdn\.', ''),
- ('s.\.', '')
- ]
-
- ShareX_urls = []
- Chibisafe_urls = []
- Erome_urls = []
- GoFile_urls = []
- Pixeldrain_urls = []
- unsupported_urls = []
-
- cookies = []
- result_links = OrderedDict()
-
- log("Starting Scrape", Fore.WHITE)
-
- for url in urls:
- url = url.replace('\n', '')
- base_domain = urlparse(url).netloc
- for old, new in replacements:
- base_domain = re.sub(old, new, base_domain)
- if base_domain in mapping_ShareX:
- if check_direct(url):
- result_links.setdefault(base_domain, OrderedDict()).setdefault("ShareX Loose Files", []).append(
- [url, url])
- else:
- ShareX_urls.append(url)
- elif base_domain in mapping_Chibisafe:
- if check_direct(url):
- result_links.setdefault(base_domain, OrderedDict()).setdefault("Chibisafe Loose Files", []).append(
- [url, url])
- else:
- Chibisafe_urls.append(url)
- elif base_domain in mapping_Erome:
- Erome_urls.append(url)
- elif base_domain in mapping_GoFile:
- GoFile_urls.append(url)
- elif base_domain in mapping_Pixeldrain:
- Pixeldrain_urls.append(url)
- else:
- unsupported_urls.append(url)
-
- def crawler_results(item):
- domain = sanitize_key(item['netloc'])
- title = re.sub(r'[\\*?:"<>|.]', "-", item['title'])
- referal = item['referal']
- url = item['url']
- cookies.extend(x for x in item['cookies'] if x not in cookies)
- result_links.setdefault(domain, OrderedDict()).setdefault(title, []).append([url, referal])
-
- dispatcher.connect(crawler_results, signal=signals.item_scraped)
- settings = get_project_settings()
- settings.set('LOG_FILE', 'logs.log')
- settings.set('TWISTED_REACTOR', "twisted.internet.asyncioreactor.AsyncioSelectorReactor")
- process = CrawlerProcess(settings)
-
- if ShareX_urls:
- process.crawl(ShareX_Spider, myurls=ShareX_urls)
- if Chibisafe_urls:
- process.crawl(Chibisafe_Spider, myurls=Chibisafe_urls)
- if Erome_urls:
- process.crawl(Erome_Spider, myurls=Erome_urls)
- if GoFile_urls:
- gofile_crawler = GofileCrawler(links=GoFile_urls)
- result_links.setdefault('gofile.io', gofile_crawler.build_targets())
- cookies.append({
- 'name': 'accountToken',
- 'value': gofile_crawler.client.token,
- })
- if Pixeldrain_urls:
- for url in Pixeldrain_urls:
- folder = url.split('/')[-1]
- if url.split('/')[-2] is 'l':
- result_links.setdefault('pixeldrain.com', OrderedDict()).setdefault("PixelDrain", []).append([f'https://pixeldrain.com/api/list/{folder}/zip', url])
- else:
- result_links.setdefault('pixeldrain.com', OrderedDict()).setdefault("PixelDrain", []).append([f'https://pixeldrain.com/api/file/{folder}?download', url])
-
- process.start()
-
- return cookies, result_links
diff --git a/cyberdrop_dl/main.py b/cyberdrop_dl/main.py
index c5c4eb6b2..d5c7f0f30 100644
--- a/cyberdrop_dl/main.py
+++ b/cyberdrop_dl/main.py
@@ -11,8 +11,8 @@ import requests
from cyberdrop_dl import __version__ as VERSION
import cyberdrop_dl.settings as settings
-from .utils.scraper import scrape
-from .utils.downloaders import get_downloaders
+from cyberdrop_dl.utils.scraper import scrape
+from cyberdrop_dl.utils.downloaders import get_downloaders
# Fixes reactor already installed error (issue using Scrapy with Asyncio)
@@ -21,7 +21,7 @@ try:
except Exception:
pass
-logging.basicConfig(level=logging.DEBUG, filename='download.log',
+logging.basicConfig(level=logging.DEBUG, filename='../download.log',
format='%(asctime)s:%(levelname)s:%(module)s:%(filename)s:%(lineno)d:%(message)s',
filemode='w')
warnings.filterwarnings("ignore", category=DeprecationWarning)
@@ -59,14 +59,14 @@ async def download_all():
nest_asyncio.apply()
clear()
version_check()
- if os.path.isfile("URLs.txt"):
+ if os.path.isfile("../URLs.txt"):
log("URLs.txt exists", Fore.WHITE)
else:
f = open("URLs.txt", "w+")
log("URLs.txt created", Fore.WHITE)
exit()
- file_object = open("URLs.txt", "r")
+ file_object = open("../URLs.txt", "r")
urls = file_object.read()
urls = regex_links(urls)
cookies, content_object = scrape(urls)
@@ -87,5 +87,6 @@ async def download_all():
def main():
asyncio.get_event_loop().run_until_complete(download_all())
+
if __name__ == '__main__':
main()
diff --git a/cyberdrop_dl/settings.py b/cyberdrop_dl/settings.py
index feabc903e..fac48f7d9 100644
--- a/cyberdrop_dl/settings.py
+++ b/cyberdrop_dl/settings.py
@@ -6,6 +6,6 @@
# include_id_in_download_folder_name = False - setting this to true will add the ID to download folder names.
threads = 0
-download_folder = "./Downloads/"
+download_folder = "../Downloads/"
download_attempts = 10
include_id_in_download_folder_name = False
diff --git a/cyberdrop_dl/utils/downloaders.py b/cyberdrop_dl/utils/downloaders.py
index 432764715..62466500a 100644
--- a/cyberdrop_dl/utils/downloaders.py
+++ b/cyberdrop_dl/utils/downloaders.py
@@ -157,6 +157,12 @@ class Downloader:
headers['Range'] = 'bytes=%d-' % resume_point
resp = await session.get(url, headers=headers, ssl=ssl_context, raise_for_status=True)
+
+ content_type = resp.headers.get('Content-Type')
+ if 'text' in content_type.lower() or 'html' in content_type.lower():
+ log(f"\nServer for {url} is either down or the file no longer exists", Fore.RED)
+ return
+
total = int(resp.headers.get('Content-Length', 0)) + resume_point
with tqdm(
total=total, unit_scale=True,
@@ -169,7 +175,7 @@ class Downloader:
progress.update(len(chunk))
await self.rename_file(filename)
except (aiohttp.client_exceptions.ClientPayloadError, aiohttp.client_exceptions.ClientOSError,
- aiohttp.client_exceptions.ServerDisconnectedError, asyncio.TimeoutError) as e:
+ aiohttp.client_exceptions.ServerDisconnectedError, asyncio.TimeoutError, FailureException) as e:
raise FailureException(e)
async def rename_file(self, filename: str) -> None:
diff --git a/cyberdrop_dl/utils/scraper.py b/cyberdrop_dl/utils/scraper.py
index 647a99f11..b9a78d144 100644
--- a/cyberdrop_dl/utils/scraper.py
+++ b/cyberdrop_dl/utils/scraper.py
@@ -157,7 +157,7 @@ def scrape(urls):
if Pixeldrain_urls:
for url in Pixeldrain_urls:
folder = url.split('/')[-1]
- if url.split('/')[-2] is 'l':
+ if url.split('/')[-2] == 'l':
result_links.setdefault('pixeldrain.com', OrderedDict()).setdefault("PixelDrain", []).append([f'https://pixeldrain.com/api/list/{folder}/zip', url])
else:
result_links.setdefault('pixeldrain.com', OrderedDict()).setdefault("PixelDrain", []).append([f'https://pixeldrain.com/api/file/{folder}?download', url])