Bulk asynchronous downloader for multiple file hosts
Python asynciobunkrcyberdropdownloaderdropboxfilestergofilegoogle-drivemediafiremegamega-nzonedrivepatreonpawchivepinterestpixeldraintransfer-ittwitchtwittervk
Complete 2.0 implementation. I should have spread this into separate commits, but I got carried away.
Jules5dee50f8146e
diff --git a/LICENSE-THIRD-PARTY b/LICENSE-THIRD-PARTYindex 166f2aebf..edfe46c32 100644--- a/LICENSE-THIRD-PARTY+++ b/LICENSE-THIRD-PARTY@@ -1 +1 @@-Forked from https://github.com/alexdotis/Chibisafe-Sharex-Scraper/tree/feadd9c14e3307d07b174abbda0c6f40b608a0a4\ No newline at end of file+Forked downloaders.py from https://github.com/alexdotis/Chibisafe-Sharex-Scraper/tree/feadd9c14e3307d07b174abbda0c6f40b608a0a4\ No newline at end of filediff --git a/README.md b/README.mdindex 40aa2c37a..0af94cc6d 100644--- a/README.md+++ b/README.md@@ -4,21 +4,20 @@# Supported SitesCyberdrop.me-DMCA.Gripe+Putme.ga-Putmega--Pixl+Pixl.isBunkr.to+~~DMCA.Gripe~~ (It's dead)+# Information-Created Using Python 3.7.4-https://www.python.org/downloads/release/python-374/+Created Using Python 3.9.6+https://www.python.org/downloads/release/python-396/-The program will take the title of the archive and create a new folder for it, and download all of the images to that folder. It'll repeat for every link you have in URLs.txt.-If there are no links in URLs.txt, it will instantly close and nothing will happen.+The program will take the title of the archive and create a new folder for it, and download all of the avilable media to that folder. It'll repeat for every link you have in URLs.txt.# Installation@@ -37,11 +36,11 @@ https://www.python.org/ftp/python/3.9.6/python-3.9.6-amd64.exeUse this installer to install python, make sure you select the box that says "ADD TO PATH"-**Arch Linux**+**Arch Linux** (Not maintained by me)There is a package on the AUR named [`cyberdropdownloader-bin`](https://aur.archlinux.org/packages/cyberdropdownloader-bin/).-This can be installed using your preffered AUR helper with a command like `paru -Sy cyberdropdownloader-bin`. You can then run the program by running `$ cyberdrop-downloader`. This will create a `URLS.txt` file in your current path which you can populate to proceed with your downloads.+This can be installed using your preferred AUR helper with a command like `paru -Sy cyberdropdownloader-bin`. You can then run the program by running `$ cyberdrop-downloader`. This will create a `URLS.txt` file in your current path which you can populate to proceed with your downloads.# UsageCopy and paste links into URLs.txt.@@ -50,3 +49,9 @@ Each link you add has to go on it's own line. (paste link, press enter, repeat).Double click on Start.bat (or Start.sh for Mac OS/Linux), it will download the needed libraries using PIP and run the program.NOTE: Mac OS X / Linux users will likely have to run the command "chmod +x Start.sh" before they can execute the script.++# Credit++The majority of the new download methodology came from alexdotis' [Chibisafe-Sharex-Scraper](https://github.com/alexdotis/Chibisafe-Sharex-Scraper).+Added to his code was the ability to take a more descriptive url object containing the album title, netloc and content urls.+The download methodology now also checks for existing files.\ No newline at end of filediff --git a/Start.bat b/Start.batindex 932ae311b..d10226009 100644--- a/Start.bat+++ b/Start.bat@@ -1,2 +1,4 @@py -m pip install -r requirements.txt --user-py downloader.py+pause+py main.py+pause\ No newline at end of filediff --git a/URLs.txt b/URLs.txtindex b7d05090d..e69de29bb 100644--- a/URLs.txt+++ b/URLs.txt@@ -1 +0,0 @@-https://bunkr.is/a/rl1mFYis\ No newline at end of filediff --git a/main.py b/main.pyindex ced3243a7..6c2af6b4d 100644--- a/main.py+++ b/main.py@@ -1,36 +1,24 @@import logging-import argparseimport asynciofrom pathlib import Path-from urllib.parse import urlparse-from utils.downloaders import get_downloaders-from utils.scrapers import get_scrapper+from utilities.scraper import scrape+from utilities.downloaders import get_downloadersimport settings-from colorama import Fore, Styleimport requestsimport osimport multiprocessing-from pathvalidate import sanitize_filename+import warnings+import readchar+logging.basicConfig(level=logging.DEBUG, filename='logs.log',- format='%(asctime)s:%(levelname)s:%(module)s:%(filename)s:%(lineno)d:%(message)s')+ format='%(asctime)s:%(levelname)s:%(module)s:%(filename)s:%(lineno)d:%(message)s',+ filemode='w')+warnings.filterwarnings("ignore", category=DeprecationWarning)SUPPORTED_URLS = {'cyberdrop.me', 'bunkr.is', 'pixl.is', 'putme.ga'}--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'- }-}-CPU_COUNT = settings.threads if settings.threads != 0 else multiprocessing.cpu_count()DOWNLOAD_FOLDER = settings.download_folder@@ -45,31 +33,10 @@ def clear():os.system('cls' if os.name == 'nt' else 'clear')-def classify_media_files(path: Path) -> None:-- images = [filename for filename in path.iterdir() if filename.suffix in FILE_FORMATS['Images']]-- videos = [filename for filename in path.iterdir() if filename.suffix in FILE_FORMATS['Videos']]-- if not images or not videos:- return-- images_folder = Path(path / 'Images')- images_folder.mkdir(exist_ok=True)- videos_folder = Path(path / 'Videos')- videos_folder.mkdir(exist_ok=True)-- # Move the images and videos to appropriate directories- for image in images:- image.rename(images_folder / image.name)- for video in videos:- video.rename(videos_folder / video.name)--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 = "1.5.7"+ current_version = "2.0.0"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)@@ -78,31 +45,28 @@ def version_check() -> None:async def main():+ clear()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 = [line for line in file_object]- for url in urls:- scrapper = get_scrapper(url)-- with scrapper:- title = DOWNLOAD_FOLDER + sanitize_filename(scrapper.get_soup().select_one('title').text)- links = scrapper.result_links()-- if not links:- logging.error(f'ValueError No links: {links}')- raise ValueError('No links found, check the URL.txt')+ 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')- downloaders = get_downloaders(links, folder=Path(title), max_workers=CPU_COUNT)+ downloaders = get_downloaders(content_object, folder=Path(DOWNLOAD_FOLDER), max_workers=CPU_COUNT)- for downloader in downloaders:- await downloader.download_content()- classify_media_files(Path(title))+ for downloader in downloaders:+ await downloader.download_content()+ log('Finished scraping. Enjoy :)', Fore.WHITE)+ print(repr(readchar.readchar()))if __name__ == '__main__':- asyncio.run(main())+ asyncio.get_event_loop().run_until_complete(main())diff --git a/requirements.txt b/requirements.txtnew file mode 100644index 000000000..83fb8116a--- /dev/null+++ b/requirements.txt@@ -0,0 +1,9 @@+asyncio~=3.4.3+requests~=2.26.0+colorama~=0.4.4+Scrapy~=2.5.1+aiofiles~=0.8.0+aiohttp~=3.8.1+tqdm~=4.62.3+sanitize-filename~=1.2.0+readchar~=3.0.4\ No newline at end of filediff --git a/utils/downloaders.py b/utils/downloaders.pyindex 3697e2751..6e1039a7f 100644--- a/utils/downloaders.py+++ b/utils/downloaders.py@@ -10,6 +10,7 @@ import aiohttp.client_exceptionsfrom requests.structures import CaseInsensitiveDictfrom tqdm import tqdmimport logging+from sanitize_filename import sanitizelogger = logging.getLogger(__name__)@@ -18,9 +19,9 @@ T_Func = TypeVar("T_Func", bound=Callable)def retry(- attempts: int,- timeout: Union[int, float] = 0,- exceptions: Iterable[Type[Exception]] = (Exception, )+ attempts: int,+ timeout: Union[int, float] = 0,+ exceptions: Iterable[Type[Exception]] = (Exception,)) -> Callable:def inner(func: T_Func) -> T_Func:@wraps(func)@@ -36,29 +37,32 @@ def retry(raise exctimes_tried += 1await asyncio.sleep(timeout)+return cast(T_Func, wrapper)+return innerclass Downloader:- def __init__(self, links: List[str], folder: Path, max_workers: int):+ def __init__(self, links: List[str], folder: Path, title: str, max_workers: int):self.links = linksself.folder = folder+ self.title = titleself.max_workers = max_workersself._semaphore = asyncio.Semaphore(max_workers)@retry(attempts=10, timeout=4, exceptions=(- aiohttp.client_exceptions.ClientPayloadError,- aiohttp.client_exceptions.ClientOSError,- aiohttp.client_exceptions.ServerDisconnectedError,- asyncio.TimeoutError+ aiohttp.client_exceptions.ClientPayloadError,+ aiohttp.client_exceptions.ClientOSError,+ aiohttp.client_exceptions.ServerDisconnectedError,+ asyncio.TimeoutError))async def download_file(- self,- url: str,- session: aiohttp.ClientSession,- headers: Optional[CaseInsensitiveDict] = None,- show_progress: bool = True+ self,+ url: str,+ session: aiohttp.ClientSession,+ headers: Optional[CaseInsensitiveDict] = None,+ show_progress: bool = True) -> bytearray:"""Download the content of given URL and return the obtained bytes."""downloaded = bytearray()@@ -77,27 +81,32 @@ class Downloader:async def store_file(self, data: bytearray, filename: str) -> None:"""Store given data into a file."""- async with aiofiles.open(self.folder / filename, mode='wb') as f:+ async with aiofiles.open(self.folder / self.title / filename, mode='wb') as f:await f.write(data)+ logger.debug("Finished " + filename)async def download_and_store(- self,- url: str,- session: aiohttp.ClientSession,- headers: Optional[CaseInsensitiveDict] = None,- show_progress: bool = True+ self,+ url: str,+ session: aiohttp.ClientSession,+ headers: Optional[CaseInsensitiveDict] = None,+ show_progress: bool = True) -> None:"""Download the content of given URL and store it in a file."""- data = await self.download_file(url, session, headers=headers, show_progress=show_progress)- filename = url.split("/")[-1]- await self.store_file(data, filename)+ 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)+ data = await self.download_file(url, session, headers=headers, show_progress=show_progress)+ await self.store_file(data, filename)async def download_all(- self,- links: Iterable[str],- session: aiohttp.ClientSession,- headers: Optional[CaseInsensitiveDict] = None,- show_progress: bool = True+ self,+ links: Iterable[str],+ session: aiohttp.ClientSession,+ headers: Optional[CaseInsensitiveDict] = None,+ show_progress: bool = True) -> None:"""Download the data from all given links and store them into corresponding files."""coros = [self.download_and_store(@@ -106,12 +115,12 @@ class Downloader:await funcasync def download_content(- self,- headers: Optional[CaseInsensitiveDict] = None,- show_progress: bool = True+ self,+ headers: Optional[CaseInsensitiveDict] = None,+ show_progress: bool = True) -> None:"""Download the content of all links and save them as files."""- self.folder.mkdir(exist_ok=True)+ (self.folder / self.title).mkdir(parents=True, exist_ok=True)async with aiohttp.ClientSession() as session:await self.download_all(self.links, session, headers=headers, show_progress=show_progress)@@ -135,7 +144,7 @@ class BunkrDownloader(Downloader):# Make a singleton value so that we can work on iterable that# would contain None objects as well.FILLVALUE = object()- iters = (iter(it), ) * chunk_size+ iters = (iter(it),) * chunk_sizefor tup in itertools.zip_longest(*iters, fillvalue=FILLVALUE):if len(tup) == chunk_size:yield tup@@ -150,21 +159,21 @@ class BunkrDownloader(Downloader):return tuple(lst)async def download_file(- self,- url: str,- session: aiohttp.ClientSession,- headers: Optional[CaseInsensitiveDict] = None,- show_progress: bool = True+ self,+ url: str,+ session: aiohttp.ClientSession,+ headers: Optional[CaseInsensitiveDict] = None,+ show_progress: bool = True) -> bytearray:url = self.bunkr_parse(url)return await super().download_file(url, session, headers=headers, show_progress=show_progress)async def download_all(- self,- links: Iterable[str],- session: aiohttp.ClientSession,- headers: Optional[CaseInsensitiveDict] = None,- show_progress: bool = True+ self,+ links: Iterable[str],+ session: aiohttp.ClientSession,+ headers: Optional[CaseInsensitiveDict] = None,+ show_progress: bool = True) -> None:"""Download the data from all given links and store them into corresponding files.@@ -176,7 +185,7 @@ class BunkrDownloader(Downloader):await super().download_all(links, session, headers=headers, show_progress=show_progress)-def get_downloaders(urls: Iterable[str], folder: Path, max_workers: int) -> List[Downloader]:+def get_downloaders(urls: dict[dict[list[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@@ -191,17 +200,13 @@ def get_downloaders(urls: Iterable[str], folder: Path, max_workers: int) -> List'putme.ga': Downloader,'cyberdrop.to': Downloader}- downloader_links = {}- for url in urls:- domain = '.'.join(urlparse(url).netloc.split('.')[-2:])- lst = downloader_links.setdefault(domain, [])- lst.append(url)+downloaders = []- for domain, urls in downloader_links.items():+ for domain, url_object in urls.items():if domain not in mapping:logging.error('Invalid URL!')raise ValueError('Invalid URL!')- downloader = mapping[domain](- urls, folder=folder, max_workers=max_workers)- downloaders.append(downloader)+ for title, urls in url_object.items():+ downloader = mapping[domain](urls, title=title, folder=folder, max_workers=max_workers)+ downloaders.append(downloader)return downloadersdiff --git a/utils/scrapers.py b/utils/scrapers.pyindex 9f9edf67e..ccfbd0fa9 100644--- a/utils/scrapers.py+++ b/utils/scrapers.py@@ -1,147 +1,104 @@-from abc import ABC, abstractmethod-from typing import Iterable, Iterator, Optional, Set, Type-from types import TracebackType+from scrapy import signals, Spider+from scrapy.crawler import CrawlerProcess+from scrapy.utils.project import get_project_settings+from scrapy.http.request import Request+from scrapy.signalmanager import dispatcherfrom urllib.parse import urlparse-import requests-from bs4 import BeautifulSoupimport logging+import re-logger = logging.getLogger(__name__)+class ShareXSpider(Spider):+ name = 'ShareX'-class Scraper(ABC):- """This class handles scraping links from a given page."""- def __init__(self, start_url: str):- self.session = requests.Session()- self.url = start_url+ def __init__(self, *args, **kwargs):+ self.myurls = kwargs.get('myurls', [])+ super(ShareXSpider, self).__init__(*args, **kwargs)- def __enter__(self) -> 'Scraper':- return self+ def start_requests(self):+ for url in self.myurls:+ yield Request(url, self.parse)- def __exit__(self, exc_type: Type[Exception], exc_val: Exception, exc_tb: TracebackType) -> None:- self.session.close()+ def parse(self, response):+ list_recent = response.css('a[id=list-most-recent-link]::attr(href)').get()+ title = response.css('title::text').get()+ yield Request(list_recent, callback=self.get_list_links, meta={'title': title})- def get_soup(self) -> BeautifulSoup:- """Get the HTML from the url and return a BeautifulSoup from it+ def get_list_links(self, response):+ links = response.meta.get('links', [])+ title = response.meta.get('title')+ links.extend(response.css('a[href*=image] img::attr(src)').getall())- Returns:- BeautifulSoup- """- response = self.session.get(self.url)- response.raise_for_status()- soup = BeautifulSoup(response.text, 'html.parser')- return soup-- def fetch_all_links(self) -> Iterator[Set[str]]:- """Scrape the URL and generate a list of href links from found anchors per page.-- Yielding will change the internal url variable to next page (until we hit last page).-- Raises:- ValueError: Url is not in sets- Yields:- Iterator[Set[str]]- """- yield self.get_page_links()-- if self.next_page_url is not None:- self.url = self.next_page_url- yield from self.fetch_all_links()-- @abstractmethod- def get_page_links(self) -> Iterable[str]:- """Scrape the page and return a list of href links from found anchors.-- This method is expected to be overridden since each site will have different- structure and obtaining links will differ.- """- raise NotImplementedError-- @property- @abstractmethod- def next_page_url(self) -> Optional[str]:- """- Gets the URL for the next page scraped from current page.-- This method is expected to be overridden since each site will have the link- to next page in a different place.-- If there is no next page, we return `None`- """- raise NotImplementedError-- @property- @abstractmethod- def previous_page_url(self) -> Optional[str]:- """Gets the URL for the previous page scraped from current page.-- This method is expected to be overridden since each site will have the link- to next page in a different place.- """-- raise NotImplementedError-- def result_links(self) -> Set[str]:- """Get all links across all pages from the start page url.-- Returns:- Set[str]: Set of urls- """- return {url for page_urls in self.fetch_all_links() for url in page_urls}---class ChibisafeScraper(Scraper):- """Handles Scraping websites built on chibisafe project."""-- def get_page_links(self) -> Iterable[str]:- soup = self.get_soup().select_one('#table')- return {anchor['href'] for anchor in soup.findAll('a', href=True)}-- @property- def next_page_url(self) -> Optional[str]:- # Chibisafe project doesn't have pagination support- return None-- @property- def previous_page_url(self) -> Optional[str]:- # Chibisafe project doesn't have pagination support- return None---class SharexScraper(Scraper):- """Handles scraping websites built on sharex project."""- def get_page_links(self) -> Iterable[str]:- soup = self.get_soup().select_one('#list-most-recent')- return {- anchor['src']- for content in soup.findAll('div', {'class': 'pad-content-listing'})- for anchor in content.find_all('img')- }-- @property- def next_page_url(self) -> Optional[str]:- soup = self.get_soup().select_one('#list-most-recent')- next_page = soup.find('a', {'data-pagination': 'next'}, href=True)+ next_page = response.css('li.pagination-next a::attr("href")').get()+ meta = {'links': links, 'title': title}if next_page is not None:- return next_page.get('href')- return None-- @property- def previous_page_url(self) -> Optional[str]:- # TODO: Implement this (even though it may not be needed at the moment- # since we have next_page_url, it kind of makes sense to have previous- # page too, you never know what you'll want to do with the class eventually- # (or if it's a library, what others will want to do with it)- raise NotImplementedError---def get_scrapper(url: str) -> Scraper:- """This function is responsible for returning a proper Scrape class given the URL."""- mapping = {- "cyberdrop.me": ChibisafeScraper,- "bunkr.is": ChibisafeScraper,- "pixl.is": SharexScraper,- "putme.ga": SharexScraper- }- url_netloc = urlparse(url).netloc- return mapping[url_netloc](url)+ yield Request(url=next_page, callback=self.get_list_links, meta=meta)+ else:+ for link in links:+ netloc = urlparse(link).netloc+ yield {'netloc': netloc, 'url': link.replace('.md.', '.').replace('.th.', '.'), 'title': title}+++class ChibisafeSpider(Spider):+ name = 'ShareX'++ def __init__(self, *args, **kwargs):+ self.myurls = kwargs.get('myurls', [])+ super(ChibisafeSpider, self).__init__(*args, **kwargs)++ def start_requests(self):+ for url in self.myurls:+ yield Request(url, self.parse)++ def parse(self, response):+ links = response.css('a[class=image]::attr(href)').getall()+ title = response.css('title::text').get()+ for link in links:+ netloc = urlparse(link).netloc+ yield {'netloc': netloc, 'url': link, 'title': title}+++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"+ return key+++def scrape(urls):+ mapping_ShareX = ["pixl.is", "putme.ga"]+ mapping_Chibisafe = ["cyberdrop.me", "bunkr.is"]+++ ShareX_urls = []+ Chibisafe_urls = []+ unsupported_urls = []+ result_links = {}++ for url in urls:+ base_domain = urlparse(url).netloc+ if base_domain in mapping_ShareX:+ ShareX_urls.append(url)+ elif base_domain in mapping_Chibisafe:+ Chibisafe_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'])++ dispatcher.connect(crawler_results, signal=signals.item_scraped)+ settings = get_project_settings()+ settings.set('LOG_LEVEL', logging.CRITICAL)+ process = CrawlerProcess(settings)+ if Chibisafe_urls: process.crawl(ChibisafeSpider, myurls=Chibisafe_urls)+ if ShareX_urls: process.crawl(ShareXSpider, myurls=ShareX_urls)+ process.start()+ return result_links