Skip to content

Bulk asynchronous downloader for multiple file hosts

Fork alexdotis/Chibisafe-Sharex-Scraper

Jules100abe049396
diff --git a/LICENSE-THIRD-PARTY b/LICENSE-THIRD-PARTY
new file mode 100644
index 000000000..a75398f75
--- /dev/null
+++ b/LICENSE-THIRD-PARTY
@@ -0,0 +1 @@
+Forked from https://github.com/alexdotis/Chibisafe-Sharex-Scraper
\ No newline at end of file
diff --git a/Start.bat b/Start.bat
deleted file mode 100644
index 3522a758c..000000000
--- a/Start.bat
+++ /dev/null
@@ -1,2 +0,0 @@
-py -m pip install -r requirements.txt --user
-py downloader.py
diff --git a/Start.sh b/Start.sh
deleted file mode 100644
index c08c66ba5..000000000
--- a/Start.sh
+++ /dev/null
@@ -1,4 +0,0 @@
-#!/bin/sh
-cd "$(dirname "$0")"
-pip3 install -r requirements.txt --user
-python3 ./downloader.py
diff --git a/downloader.py b/downloader.py
deleted file mode 100644
index 244c55de8..000000000
--- a/downloader.py
+++ /dev/null
@@ -1,227 +0,0 @@
-# Cyberdrop Gallery Downloader Originally by nixxin
-# Made better(?) by Jules--Winnfield
-
-import requests
-import os
-import re
-import time
-from colorama import Fore, Style
-from geturls import Extrair_Links
-from multiprocessing import Pool
-from bs4 import BeautifulSoup
-import multiprocessing
-import settings
-
-
-class SizeError(Exception):
- """Exception raised for errors in the input.
- Attributes:
- expression -- input expression in which the error occurred
- message -- explanation of the error
- """
-
- def __init__(self, expression, message):
- self.expression = expression
- self.message = message
-
-
-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 download(passed_from_main):
- _path = passed_from_main[0]
- _referer = bytes(passed_from_main[1], "utf-8")
- _item = passed_from_main[2]
- _timeout = passed_from_main[3]
-
- attempts = 1
- allowed_attempts = (settings.file_attempts + 1) if settings.file_attempts != 0 else 0
-
- try:
- while True:
- filename = _item[_item.rfind("/") + 1:]
- rstr = r"[\/\\\:\*\?\"\<\>\|]" # '/ \ : * ? " < > | .'
- filename = re.sub(rstr, "_", filename)
- temp_filename = f'{filename}.download'
- _url = _item
-
- if allowed_attempts != 0 and attempts >= allowed_attempts:
- log("\tHit user specified attempt limit" + " for " + filename + " skipping file", Fore.RED)
- break
-
- else:
- if attempts != 1:
- log("\tRetrying " + filename + "...", Fore.YELLOW)
- try:
- if filename == "cyberdrop.me-downloaders":
- break
-
- headers = {'referer': _referer}
- resume = False
-
- if not resume and os.path.isfile(_path + str(filename)):
- log("\t" + filename + " already exists.", Fore.GREEN)
- break
-
- stored_file_size = None
- if os.path.isfile(_path + str(temp_filename)):
- stored_file_size = os.path.getsize(_path + str(temp_filename))
- log("\t" + filename + f" already exists (partial, {stored_file_size} B).", Fore.LIGHTBLACK_EX)
- headers['Range'] = f'bytes={stored_file_size}-'
- resume = True
-
- log("\tDownloading " + filename + "...", Fore.LIGHTBLACK_EX)
-
- try:
- response = requests.get(_url, stream=True, timeout=_timeout, headers=headers)
- response.raise_for_status()
- incoming_file_size = int(response.headers['Content-length'])
- with open(_path + str(temp_filename), "ab" if resume else "wb") as out_file:
- for chunk in response.iter_content(chunk_size=50000):
- if chunk:
- out_file.write(chunk)
- except requests.exceptions.HTTPError as err:
- log("\t"+str(err), Fore.RED)
-
- if response.status_code == 429:
- # Bunkr doesn't return a 'retry-at' header element for some godly reason.
- time_to_sleep = 5*attempts
- log("\tFailed attempt {} for {}. Sleeping thread for {} seconds.".format(attempts, filename, time_to_sleep), Fore.RED)
- time.sleep(int(time_to_sleep))
- else:
- log("\tFailed attempt {} for {}.".format(attempts, filename), Fore.RED)
- attempts += 1
- continue
-
- if os.path.isfile(_path + str(temp_filename)):
- total_file_size = incoming_file_size if stored_file_size is None else (
- incoming_file_size + stored_file_size)
- stored_file_size = os.path.getsize(_path + str(temp_filename))
- if total_file_size == stored_file_size:
- os.rename(_path + str(temp_filename), _path + str(filename))
- log("\tFinished " + filename, Fore.GREEN)
- break
- else:
- raise SizeError("File Size Specified: {} bytes, File Size Obtained: {} bytes".format(
- total_file_size, stored_file_size), "These file sizes don't match")
- else:
- log("\tSomething went wrong" + " for " + filename, Fore.RED)
- attempts += 1
- except Exception as e:
- log(e, Fore.RED)
- log("\tFailed attempt " + str(attempts) + " for " + filename, Fore.RED)
- attempts += 1
-
- except Exception as e:
- print(e)
- print("Failed to Download")
-
-
-if __name__ == '__main__':
- log("", Fore.RESET)
-
- response = requests.get("https://api.github.com/repos/Jules-WinnfieldX/CyberDropDownloader/releases/latest")
- latest_version = response.json()["tag_name"]
- current_version = "1.5.8"
-
- clear()
-
- 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")
-
- headers = {'headers': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:51.0) Gecko/20100101 Firefox/51.0'}
-
- cpu_count = settings.threads if settings.threads != 0 else multiprocessing.cpu_count()
- download_folder = settings.download_folder
- timeout = settings.timeout
-
- if download_folder == "./Downloads/":
- if not os.path.exists(download_folder):
- os.makedirs(download_folder)
- else:
- if not os.path.exists(download_folder):
- log("The download folder specified (" + download_folder + ") does not exist ", Fore.RED)
-
- if os.path.isfile("URLs.txt"):
- print("URLs.txt exists")
- else:
- f = open("URLs.txt", "w+")
- print("URLs.txt created")
-
- if os.stat("URLs.txt").st_size == 0:
- print("Please put URLs in URLs.txt")
-
- file_object = open("URLs.txt", "r")
- for line in file_object:
- url = line.rstrip()
-
- page = requests.get(url)
- soup = BeautifulSoup(page.text, "html.parser")
-
- try:
- if 'cyberdrop' in url.lower():
- directory_name = soup.select('h1.has-text-centered')[0].text.strip()
- directory_name = directory_name.split("–")[0]
-
- elif 'putme.ga' in url.lower() or 'pixl' in url.lower():
- directory_name = soup.find("meta", {"property": "og:title"}).attrs['content']
-
- elif 'bunk' in url.lower():
- directory_name = soup.select('h1.title')[0].text.strip()
- # Artificial limit to bypass rate limitting
- cpu_count = cpu_count if cpu_count < 3 else 2
- except:
- print("Skipping URL: {}".format(url))
- print("Please check the URL and if it's valid please create a github issue.")
- continue
-
- rstr = r"[\/\\\:\*\?\"\<\>\|\.]" # '/ \ : * ? " < > | .'
- directory_name = re.sub(rstr, "_", directory_name)
- directory_name += "/"
- path = download_folder+directory_name
-
- print("\n======================================================\n")
-
- print("\nCollecting file links from " + url + "...")
- links = Extrair_Links(url)
- links = {k: v for k, v in links.items() if v is not None}
-
- if not links:
- print()
- input(url + " Couldn't find pictures.")
- exit()
-
- print()
- print("\tURL\t" + url)
- print("\tDIR\t" + path)
- print()
- if not (os.path.isdir(path)):
- try:
- os.mkdir(path)
- print()
- log("Created directory {dir}".format(dir=path), Fore.GREEN)
- except OSError as e:
- log("Creation of directory {dir} failed: {err}".format(dir=path, err=e), Fore.RED)
- print()
-
- pass_to_func = []
- for referer, link_list in links.items():
- for link in link_list:
- pass_to_func.append([path, referer, link, timeout])
-
- print("Downloading " + str(len(pass_to_func)) + " files...")
- pool = Pool(processes=cpu_count)
- proc = pool.map_async(download, pass_to_func)
- proc.wait()
- pool.close()
-
- exitText = input("\nFinished. Press enter to quit.")
diff --git a/geturls.py b/geturls.py
deleted file mode 100644
index 1b942df84..000000000
--- a/geturls.py
+++ /dev/null
@@ -1,125 +0,0 @@
-import requests
-from bs4 import BeautifulSoup
-
-video_extensions = ['.mp4', '.wmv', '.m4v', '.mov']
-
-
-def cyberdrop_extractor(soup, base_URL):
- links = {base_URL: None}
- if 'cyberdrop' in base_URL.lower():
- for link in soup.find_all(id="file"):
- final_link = link.get('href')
- if len(str(final_link)) > 30:
- final_link = final_link.replace('.nl/', '.cc/')
- if isinstance(links[base_URL], list):
- links[base_URL].append(final_link)
- else:
- links[base_URL] = [final_link]
- return links
-
-
-def bunkr_extractor(soup, base_URL):
- links = {base_URL: None}
- for link in soup.find_all(class_="image"):
- final_link = link.get('href')
- if any(video_extension in final_link.lower() for video_extension in video_extensions):
- new_base_URL = final_link.replace('https://cdn.bunkr.is/', 'https://stream.bunkr.is/v/')
- final_link = final_link.replace('https://cdn.bunkr.is/', 'https://stream.bunkr.is/d/')
- if new_base_URL in links:
- links[new_base_URL].append(final_link)
- else:
- links[new_base_URL] = [final_link]
- continue
- if isinstance(links[base_URL], list):
- links[base_URL].append(final_link)
- else:
- links[base_URL] = [final_link]
- return links
-
-
-def dmca_gripe_extractor(soup, base_URL):
- links = {base_URL: None}
- for link in soup.find_all('a', {'class': 'download-button'}):
- potential_final_link = link.get('href')
- if any(videoExtension in potential_final_link.lower() for videoExtension in video_extensions):
- # extract direct video links from download page. This will likely break eventually.
- try:
- page = requests.get(potential_final_link)
- data = page.text
- soup = BeautifulSoup(data, features="html5lib")
-
- for link in soup.find_all('a', {'class': 'btn btn-dl'}):
- suffix = link.get('href')
- if isinstance(links[potential_final_link], list):
- links[potential_final_link].append("https://share.dmca.gripe" + suffix)
- else:
- links[potential_final_link] = ["https://share.dmca.gripe" + suffix]
- except Exception as e:
- print(e)
- return None
- elif len(str(potential_final_link)) > 30:
- if isinstance(links[base_URL], list):
- links[base_URL].append(potential_final_link)
- else:
- links[base_URL] = [potential_final_link]
- return links
-
-
-def multi_page_extractor(soup, base_URL):
- # First correct any 'bad' URLs by getting the real embedded url from the page itself
- url = soup.find(attrs={"data-text": "album-name"}).get('href')
- url += "/?sort=date_asc&page=1"
- links = {base_URL: None}
-
- while True:
- request = requests.get(url)
- soup = BeautifulSoup(request.text, 'html.parser')
- # Get image links
- html_filter = soup.find('div', {'class': 'pad-content-listing'})
- broken_links = [image["src"] for image in html_filter.findAll("img")]
- for brokenLink in broken_links:
- final_link = brokenLink.replace('.md.', '.').replace('.th.', '.')
- if url in links:
- if isinstance(links[url], list):
- links[url].append(final_link)
- else:
- links[url] = [final_link]
-
- # Searches for next page link
- next_page = soup.find("li", {'class': 'pagination-next'})
- if next_page is None:
- return links
- else:
- for child in next_page.children:
- child_URL = child.get("href")
- if child_URL:
- url = child_URL
- else:
- return links
-
-
-def Extrair_Links(base_URL):
- # Extract links from gallery
- try:
- page = requests.get(base_URL)
- data = page.text
- soup = BeautifulSoup(data, features="html5lib")
- links = {}
-
- if 'cyberdrop' in base_URL.lower():
- links = cyberdrop_extractor(soup, base_URL)
-
- elif 'bunkr' in base_URL.lower():
- links = bunkr_extractor(soup, base_URL)
-
- elif 'dmca.gripe' in base_URL.lower():
- links = dmca_gripe_extractor(soup, base_URL)
-
- elif 'putme.ga' in base_URL.lower() or 'pixl' in base_URL.lower():
- links = multi_page_extractor(soup, base_URL)
-
- except Exception as e:
- print(e)
- return None
- else:
- return links
diff --git a/main.py b/main.py
new file mode 100644
index 000000000..daaddb6a3
--- /dev/null
+++ b/main.py
@@ -0,0 +1,113 @@
+import logging
+import argparse
+import asyncio
+from pathlib import Path
+from urllib.parse import urlparse
+from utils.downloaders import get_downloaders
+from utils.scrapers import get_scrapper
+
+logging.basicConfig(
+ level=logging.DEBUG,
+ filename='logs.log',
+ format='%(asctime)s:%(levelname)s:%(module)s:%(filename)s:%(lineno)d:%(message)s'
+)
+
+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'
+ }
+}
+
+
+def classify_media_files(path: Path) -> None:
+ """Sort out files and videos to their own directories.
+
+ Args:
+ path (Path): Path containing both images and files to be classified.
+ """
+
+ 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 parse_args() -> argparse.Namespace:
+ """Parse out the command line arguments."""
+ parser = argparse.ArgumentParser(
+ description='Simple Script written in Python for download galleries of images / videos',
+ epilog="Enjoy!!!"
+ )
+ parser.add_argument(
+ '-u', '--url',
+ help=f'The url which contains images or videos. Supported links: {", ".join(SUPPORTED_URLS)}',
+ required=False,
+ action='store'
+ )
+ parser.add_argument(
+ '-p', '--progress',
+ help='Show progress bar from each url. By default its False',
+ action='store_true'
+ )
+ parser.add_argument(
+ '-w', '--max-workers',
+ help='Define the maximum amount of workers for downloading.',
+ default=20,
+ type=int
+ )
+
+ args = parser.parse_args()
+ if args.url:
+ if not urlparse(args.url).netloc in SUPPORTED_URLS:
+ logging.error(f'Unsupported URL:{args.url}')
+ raise ValueError('Unsupported URL link!')
+ return args
+
+
+async def main() -> None:
+ args = parse_args()
+ if args.url:
+ scrapper = get_scrapper(args.url)
+ with scrapper:
+ title = 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.')
+
+ downloaders = get_downloaders(links, folder=Path(
+ title), max_workers=args.max_workers)
+
+ for downloader in downloaders:
+ await downloader.download_content(show_progress=args.progress)
+ classify_media_files(Path(title))
+
+
+if __name__ == '__main__':
+ asyncio.run(main())
+
+
+# TODO: Re-add a way to redownload failed URLs and perhaps log them with the use of logging library
diff --git a/requirements.txt b/requirements.txt
deleted file mode 100644
index 31c2c2750..000000000
--- a/requirements.txt
+++ /dev/null
@@ -1,19 +0,0 @@
-args==0.1.0
-astroid==2.3.3
-beautifulsoup4==4.8.2
-bs4==0.0.1
-certifi==2019.11.28
-chardet
-clint==0.5.1
-colorama==0.4.3
-idna==2.8
-isort==4.3.21
-lazy-object-proxy==1.4.3
-mccabe==0.6.1
-pylint==2.4.4
-six==1.13.0
-soupsieve==1.9.5
-urllib3
-wrapt==1.11.2
-html5lib
-requests
diff --git a/settings.py b/settings.py
deleted file mode 100644
index 901265219..000000000
--- a/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
-# file_attempts = 0 (will try infinitely), making it 5 as an example will try to download 5 times and then skip.
-# timeout is measured in seconds
-
-threads = 0
-download_folder = "./Downloads/"
-file_attempts = 0
-timeout = 30
\ No newline at end of file
diff --git a/URLs.txt b/utils/__init__.py
similarity index 100%
rename from URLs.txt
rename to utils/__init__.py
diff --git a/utils/downloaders.py b/utils/downloaders.py
new file mode 100644
index 000000000..3697e2751
--- /dev/null
+++ b/utils/downloaders.py
@@ -0,0 +1,207 @@
+import asyncio
+import itertools
+from functools import wraps
+from pathlib import Path
+from typing import Any, Callable, Iterable, List, Optional, Tuple, Type, TypeVar, Union, cast
+from urllib.parse import urljoin, urlparse
+import aiofiles
+import aiohttp
+import aiohttp.client_exceptions
+from requests.structures import CaseInsensitiveDict
+from tqdm import tqdm
+import logging
+
+logger = logging.getLogger(__name__)
+
+T = TypeVar("T")
+T_Func = TypeVar("T_Func", bound=Callable)
+
+
+def retry(
+ attempts: int,
+ timeout: Union[int, float] = 0,
+ exceptions: Iterable[Type[Exception]] = (Exception, )
+) -> Callable:
+ def inner(func: T_Func) -> T_Func:
+ @wraps(func)
+ async def wrapper(*args, **kwargs) -> Any:
+ times_tried = 0
+ 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
+
+
+class Downloader:
+ def __init__(self, links: List[str], folder: Path, max_workers: int):
+ self.links = links
+ self.folder = folder
+ self.max_workers = max_workers
+ self._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
+ ))
+ async def download_file(
+ 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()
+ async with self._semaphore:
+ resp = await session.get(url, headers=headers)
+ total = int(resp.headers.get('Content-Length', 0))
+ with tqdm(
+ total=total, unit_scale=True,
+ unit='B', leave=False,
+ desc=url, disable=(not show_progress)
+ ) as progress:
+ async for chunk, _ in resp.content.iter_chunks():
+ downloaded.extend(chunk)
+ progress.update(len(chunk))
+ return downloaded
+
+ 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:
+ await f.write(data)
+
+ async def download_and_store(
+ 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)
+
+ async def download_all(
+ 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(
+ link, session, headers, show_progress) for link in links]
+ for func in tqdm(asyncio.as_completed(coros), total=len(coros), desc='Processing'):
+ await func
+
+ async def download_content(
+ 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)
+ async with aiohttp.ClientSession() as session:
+ await self.download_all(self.links, session, headers=headers, show_progress=show_progress)
+
+
+class BunkrDownloader(Downloader):
+ @staticmethod
+ def bunkr_parse(url: str) -> str:
+ """Fix the URL for bunkr.is and construct the headers."""
+ changed_url = url.replace('cdn.bunkr', 'stream.bunkr').split('/')
+ changed_url.insert(3, 'v')
+ changed_url = ''.join(map(lambda x: urljoin('/', x), changed_url))
+ return changed_url.replace('/v/', '/d/')
+
+ @staticmethod
+ def pairwise_skipping(it: Iterable[T], chunk_size: int) -> Tuple[T, ...]:
+ """Iterate over tuples of the iterable of size `chunk_size` at a time.
+
+ If the elements can't be evenely split, the last tuple will be
+ shrunk to accommodate the rest of the elements.
+ """
+ # 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
+ for tup in itertools.zip_longest(*iters, fillvalue=FILLVALUE):
+ if len(tup) == chunk_size:
+ yield tup
+ else:
+ # Adjust the size of the last tuple to only contain the
+ # remaining elements
+ lst = []
+ for el in tup:
+ if el is FILLVALUE:
+ break
+ lst.append(el)
+ return tuple(lst)
+
+ async def download_file(
+ 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
+ ) -> None:
+ """Download the data from all given links and store them into corresponding files.
+
+ We override this method to only make requests to 2 links at a time,
+ since bunkr.is can't handle more traffic and causes errors.
+ """
+ chunked_links = self.pairwise_skipping(self.links, chunk_size=2)
+ for links in chunked_links:
+ 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]:
+ """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.
+ """
+ mapping = {
+ 'cyberdrop.me': Downloader,
+ 'bunkr.is': BunkrDownloader,
+ 'pixl.is': Downloader,
+ '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():
+ 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)
+ return downloaders
diff --git a/utils/scrapers.py b/utils/scrapers.py
new file mode 100644
index 000000000..9f9edf67e
--- /dev/null
+++ b/utils/scrapers.py
@@ -0,0 +1,147 @@
+from abc import ABC, abstractmethod
+from typing import Iterable, Iterator, Optional, Set, Type
+from types import TracebackType
+from urllib.parse import urlparse
+import requests
+from bs4 import BeautifulSoup
+import logging
+
+logger = logging.getLogger(__name__)
+
+
+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 __enter__(self) -> 'Scraper':
+ return self
+
+ def __exit__(self, exc_type: Type[Exception], exc_val: Exception, exc_tb: TracebackType) -> None:
+ self.session.close()
+
+ def get_soup(self) -> BeautifulSoup:
+ """Get the HTML from the url and return a BeautifulSoup from it
+
+ 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)
+ 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)