Skip to content

Bulk asynchronous downloader for multiple file hosts

Fix imports problem and replace `settings.py`

rdnkarchiver72e707dca213
diff --git a/.gitignore b/.gitignore
index b17ae8889..515803fb3 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,7 +1,9 @@
# project stuff
Downloads/
-download.log
+*.log
# Python stuff
.venv/
__pycache__/
+*.egg-info/
+build/
diff --git a/Pipfile.lock b/Pipfile.lock
index f6ad71d54..ffe544d7e 100644
--- a/Pipfile.lock
+++ b/Pipfile.lock
@@ -643,7 +643,7 @@
"sha256:1e61c37477a1626458e36f7b1d82aa5c9b094fa4802892072e49de9c60c4c926",
"sha256:8abb2f1d86890a2dfb989f9a77cfcfd3e47c2a354b01111771326f8aa26e0254"
],
- "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2'",
+ "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'",
"version": "==1.16.0"
},
"tldextract": {
@@ -656,11 +656,11 @@
},
"tqdm": {
"hashes": [
- "sha256:1d9835ede8e394bb8c9dcbffbca02d717217113adc679236873eeaac5bc0b3cd",
- "sha256:e643e071046f17139dea55b880dc9b33822ce21613b4a4f5ea57f202833dbc29"
+ "sha256:4230a49119a416c88cc47d0d2d32d5d90f1a282d5e497d49801950704e49863d",
+ "sha256:6461b009d6792008d0000e1b0c7ca50195ec78c0e808a3a6b668a56a3236c3a5"
],
"index": "pypi",
- "version": "==4.63.0"
+ "version": "==4.63.1"
},
"twisted": {
"hashes": [
diff --git a/Start.bat b/Start.bat
deleted file mode 100644
index e2932d009..000000000
--- a/Start.bat
+++ /dev/null
@@ -1,4 +0,0 @@
-py -m pip install -r requirements.txt --user
-pause
-py ./cyberdrop_dl/main.py
-pause
\ No newline at end of file
diff --git a/Start.sh b/Start.sh
deleted file mode 100644
index 9c99d61e4..000000000
--- a/Start.sh
+++ /dev/null
@@ -1,4 +0,0 @@
-#!/bin/sh
-cd "$(dirname "$0")"
-pip3 install -r requirements.txt --user
-python3 ./cyberdrop_dl/main.py
diff --git a/cyberdrop_dl/main.py b/cyberdrop_dl/main.py
index d5c7f0f30..47b8e4922 100644
--- a/cyberdrop_dl/main.py
+++ b/cyberdrop_dl/main.py
@@ -1,18 +1,17 @@
+import argparse
import asyncio
import logging
import os
from pathlib import Path
import re
-import warnings
from colorama import Fore, Style
import nest_asyncio
import requests
-from cyberdrop_dl import __version__ as VERSION
-import cyberdrop_dl.settings as settings
-from cyberdrop_dl.utils.scraper import scrape
-from cyberdrop_dl.utils.downloaders import get_downloaders
+from . import __version__ as VERSION
+from .utils.scraper import scrape
+from .utils.downloaders import get_downloaders
# Fixes reactor already installed error (issue using Scrapy with Asyncio)
@@ -21,21 +20,30 @@ try:
except Exception:
pass
-logging.basicConfig(level=logging.DEBUG, filename='../download.log',
+def parse_args():
+ parser = argparse.ArgumentParser(description='Bulk downloader for multiple file hosts')
+ parser.add_argument("-V", "--version", action="version", version="%(prog)s " + VERSION)
+ parser.add_argument("-i", "--input-file", help="file containing links to download", default="URLs.txt")
+ parser.add_argument("-o", "--output-folder", help="folder to download files to", default='Downloads')
+ parser.add_argument("--threads", help="number of threads to use (0 = max)", default=0)
+ parser.add_argument("--attempts", help="number of attempts to download each file", default=10)
+ parser.add_argument("--include-id", help="include the ID in the download folder name", action="store_true")
+ args = parser.parse_args()
+ return args
+
+
+logging.basicConfig(level=logging.DEBUG, filename=Path("downloader.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
+def log(text, style = Fore.WHITE) -> None:
+ """Wrapper around print() to add color to text"""
print(style + str(text) + Style.RESET_ALL)
-def clear():
- # Clears command window
+def clear() -> None:
+ """Clears the terminal screen"""
os.system('cls' if os.name == 'nt' else 'clear')
@@ -46,7 +54,8 @@ def version_check() -> None:
if latest_version != 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")
+ if input("Keep going? (Y/n) ") == "n":
+ exit()
clear()
@@ -55,38 +64,40 @@ def regex_links(urls) -> list:
return all_links
-async def download_all():
+async def download_all(args: argparse.Namespace):
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)
+ input_file = Path(args.input_file)
+ if not os.path.isfile(input_file):
+ Path.touch(input_file)
+ log(f"{input_file} created. Populate it and retry.")
+ exit(1)
+
+ with open(input_file, "r") as f:
+ urls = regex_links(f.read())
+ cookies, content_object = scrape(urls, args.include_id)
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))
+ downloaders = get_downloaders(content_object, cookies=cookies, folder=Path(args.output_folder), attempts=args.attempts, threads=args.threads)
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)
+ log('Finished scraping. Enjoy :)')
+ log('If you have ".download" files remaining, rerun this program. You most likely ran into download attempts limit')
def main():
- asyncio.get_event_loop().run_until_complete(download_all())
+ args = parse_args()
+ asyncio.get_event_loop().run_until_complete(download_all(args))
if __name__ == '__main__':
- main()
+ print("""
+ STOP! If you're just trying to download files, check the README.md file for instructions.
+ If you're developing this project, use start.py instead.
+ """)
+ exit()
diff --git a/cyberdrop_dl/settings.py b/cyberdrop_dl/settings.py
deleted file mode 100644
index fac48f7d9..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
index 53f9538bf..bc7207c56 100644
--- a/cyberdrop_dl/utils/crawlers/Chibisafe_Spider.py
+++ b/cyberdrop_dl/utils/crawlers/Chibisafe_Spider.py
@@ -4,8 +4,6 @@ from urllib.parse import urljoin, urlparse
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': {
@@ -44,6 +42,7 @@ class Chibisafe_Spider(Spider):
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):
@@ -73,7 +72,7 @@ class Chibisafe_Spider(Spider):
try:
title = response.css('h1[id=title]::text').get()
title = title.replace(r"\n", "").strip()
- if title_setting:
+ if self.include_id:
title = title + " - " + response.url.split('/')[-1]
except Exception as e:
title = response.url.split('/')[-1]
diff --git a/cyberdrop_dl/utils/crawlers/Erome_Spider.py b/cyberdrop_dl/utils/crawlers/Erome_Spider.py
index 68a918653..c6ba8abb5 100644
--- a/cyberdrop_dl/utils/crawlers/Erome_Spider.py
+++ b/cyberdrop_dl/utils/crawlers/Erome_Spider.py
@@ -4,14 +4,13 @@ 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', [])
+ self.include_id = kwargs.get('include_id', False)
super(Erome_Spider, self).__init__(*args, **kwargs)
def start_requests(self):
@@ -24,7 +23,7 @@ class Erome_Spider(Spider):
try:
title = response.css('div[class="col-sm-12 page-content"] h1::text').get()
- if title_setting:
+ if self.include_id:
title = title + " - " + response.url.split('/')[-1]
except Exception as e:
title = response.url.split('/')[-1]
diff --git a/cyberdrop_dl/utils/crawlers/ShareX_Spider.py b/cyberdrop_dl/utils/crawlers/ShareX_Spider.py
index 97063f483..a418a89c3 100644
--- a/cyberdrop_dl/utils/crawlers/ShareX_Spider.py
+++ b/cyberdrop_dl/utils/crawlers/ShareX_Spider.py
@@ -4,13 +4,12 @@ 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', [])
+ self.include_id = kwargs.get('include_id', False)
super(ShareX_Spider, self).__init__(*args, **kwargs)
def start_requests(self):
@@ -28,7 +27,7 @@ class ShareX_Spider(Spider):
try:
title = response.css('div[class=header] h1 strong::text').get()
title = title.replace(r"\n", "").strip()
- if title_setting:
+ if self.include_id:
titlep2 = response.url.split('/')
titlep2 = [s for s in titlep2 if "." in s][-1]
title = title + " - " + titlep2
@@ -49,7 +48,7 @@ class ShareX_Spider(Spider):
try:
title = response.css('a[data-text=album-name]::text').get()
title = title.replace(r"\n", "").strip()
- if title_setting:
+ if self.include_id:
titlep2 = response.url.split('/')
titlep2 = [s for s in titlep2 if "." in s][-1]
title = title + " - " + titlep2
diff --git a/cyberdrop_dl/utils/downloaders.py b/cyberdrop_dl/utils/downloaders.py
index 62466500a..d765c91e1 100644
--- a/cyberdrop_dl/utils/downloaders.py
+++ b/cyberdrop_dl/utils/downloaders.py
@@ -7,7 +7,7 @@ from pathlib import Path
import ssl
import time
import traceback
-from typing import Any, cast, Callable, Iterable, Optional, Type, TypeVar, Union
+from typing import Iterable, Optional
import aiofiles
import aiofiles.os
@@ -19,15 +19,10 @@ 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': {
@@ -58,27 +53,18 @@ class FailureException(Exception):
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
+def retry(f):
+ @wraps(f)
+ async def wrapper(self, *args, **kwargs):
+ for i in range(self.attempts):
+ try:
+ return await f(self, *args, **kwargs)
+ except FailureException:
+ if i == self.attempts - 1:
+ raise
+ logger.debug('Retrying...')
+ time.sleep(4)
+ return wrapper
async def throttle(self, url: yarl.URL) -> None:
@@ -109,11 +95,12 @@ async def throttle(self, url: yarl.URL) -> None:
class Downloader:
- def __init__(self, links: list[list[str]], morsels, folder: Path, title: str, max_workers: int):
+ def __init__(self, links: list[list[str]], morsels, folder: Path, title: str, attempts: int, max_workers: int):
self.links = links
self.morsels = morsels
self.folder = folder
self.title = title
+ self.attempts = attempts
self.max_workers = max_workers
self._semaphore = asyncio.Semaphore(max_workers)
self.delay = {'media-files.bunkr.is': 2}
@@ -121,7 +108,7 @@ class Downloader:
"""Changed from aiohttp exceptions caught to FailureException to allow for partial downloads."""
- @retry(attempts=download_attempts, timeout=4, exceptions=FailureException)
+ @retry
async def download_file(
self,
url: str,
@@ -258,7 +245,7 @@ def simple_cookies(cookies):
return morsels
-def get_downloaders(urls: dict[str, dict[str, list[str]]], cookies: Iterable[str], folder: Path) -> list[Downloader]:
+def get_downloaders(urls: dict[str, dict[str, list[str]]], cookies: Iterable[str], folder: Path, attempts: int, threads: 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
the first one, so we need to classify them one by one, sort them to
@@ -274,6 +261,6 @@ def get_downloaders(urls: dict[str, dict[str, list[str]]], cookies: Iterable[str
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)
+ downloader = Downloader(urls, morsels=morsels, title=title, folder=folder, attempts=attempts, max_workers=max_workers)
downloaders.append(downloader)
return downloaders
diff --git a/cyberdrop_dl/utils/scraper.py b/cyberdrop_dl/utils/scraper.py
index d889f96a4..9ac42a4ec 100644
--- a/cyberdrop_dl/utils/scraper.py
+++ b/cyberdrop_dl/utils/scraper.py
@@ -70,7 +70,7 @@ def check_direct(url):
return False
-def scrape(urls):
+def scrape(urls, include_id: bool):
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"]
@@ -137,18 +137,18 @@ def scrape(urls):
dispatcher.connect(crawler_results, signal=signals.item_scraped)
settings = get_project_settings()
- settings.set('LOG_FILE', '../download.log')
+ settings.set('LOG_FILE', 'downloader.log')
settings.set('TWISTED_REACTOR', "twisted.internet.asyncioreactor.AsyncioSelectorReactor")
process = CrawlerProcess(settings)
if ShareX_urls:
- process.crawl(ShareX_Spider, myurls=ShareX_urls)
+ process.crawl(ShareX_Spider, myurls=ShareX_urls, include_id=include_id)
if Chibisafe_urls:
- process.crawl(Chibisafe_Spider, myurls=Chibisafe_urls)
+ process.crawl(Chibisafe_Spider, myurls=Chibisafe_urls, include_id=include_id)
if Erome_urls:
- process.crawl(Erome_Spider, myurls=Erome_urls)
+ process.crawl(Erome_Spider, myurls=Erome_urls, include_id=include_id)
if GoFile_urls:
- gofile_crawler = GofileCrawler(links=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',
diff --git a/start.py b/start.py
new file mode 100644
index 000000000..8fa74ce07
--- /dev/null
+++ b/start.py
@@ -0,0 +1,10 @@
+from cyberdrop_dl.main import main as main_dl
+
+
+if __name__ == '__main__':
+ print("""
+ WAIT! If you're just trying to download files, check the README.md file for instructions.
+ This file is intended for development usage ONLY.
+ """)
+ if input("Keep going? (y/N) ") == "y":
+ main_dl()