Skip to content

Bulk asynchronous downloader for multiple file hosts

Fix some pylint warnings

Arkadiy Illarionovbfdc27be36ca
diff --git a/cyberdrop_dl/main.py b/cyberdrop_dl/main.py
index ebbf3557c..c81e1b551 100644
--- a/cyberdrop_dl/main.py
+++ b/cyberdrop_dl/main.py
@@ -83,7 +83,7 @@ async def download_all(args: argparse.Namespace):
args.skip_putmega, args.skip_redgif, args.skip_saint)
content_object = await scrape(links, args.include_id, thotsbay_auth, args.separate_posts, skip_data)
if await content_object.is_empty():
- logging.error(f'ValueError No links')
+ logging.error('ValueError No links')
await log("No links found, check the URL.txt\nIf the link works in your web browser, "
"please open an issue ticket with me.", Fore.RED)
await log("This program does not currently support password protected albums.", Fore.RED)
diff --git a/cyberdrop_dl/utils/base_functions.py b/cyberdrop_dl/utils/base_functions.py
index b61e8af7d..a4a776f10 100644
--- a/cyberdrop_dl/utils/base_functions.py
+++ b/cyberdrop_dl/utils/base_functions.py
@@ -12,7 +12,7 @@ from yarl import URL
FILE_FORMATS = {
'Images': {
'.jpg', '.jpeg', '.png', '.gif',
- '.gif', '.webp', '.jpe', '.svg',
+ '.webp', '.jpe', '.svg',
'.tif', '.tiff', '.jif',
},
'Videos': {
@@ -38,8 +38,8 @@ MAX_FILENAME_LENGTH = 100
logger = logging.getLogger(__name__)
-async def sanitize(input: str) -> str:
- return re.sub(r'[<>:"/\\|?*\']', "", input)
+async def sanitize(name: str) -> str:
+ return re.sub(r'[<>:"/\\|?*\']', "", name)
async def log(text, style=Fore.WHITE) -> None:
@@ -57,9 +57,9 @@ async def make_title_safe(title: str):
return title
-async def purge_dir(dir, in_place=True):
+async def purge_dir(dirname, in_place=True):
deleted = []
- dir_tree = list(os.walk(dir, topdown=False))
+ dir_tree = list(os.walk(dirname, topdown=False))
for tree_element in dir_tree:
sub_dir = tree_element[0]
@@ -93,7 +93,4 @@ async def check_direct(url: 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'cdn..bunkr...', r'media-files.bunkr...', r'jpg.church/images/...',
r'simp..jpg.church']
- for domain in mapping_direct:
- if re.search(domain, url.host):
- return True
- return False
+ return any(re.search(domain, url.host) for domain in mapping_direct)
diff --git a/cyberdrop_dl/utils/crawlers/Bunkr_Spider.py b/cyberdrop_dl/utils/crawlers/Bunkr_Spider.py
index 0799bbb05..9ee2eab14 100644
--- a/cyberdrop_dl/utils/crawlers/Bunkr_Spider.py
+++ b/cyberdrop_dl/utils/crawlers/Bunkr_Spider.py
@@ -1,7 +1,8 @@
+import json
+
from bs4 import BeautifulSoup
from colorama import Fore
from yarl import URL
-import json
from ..base_functions import log, logger, make_title_safe, ssl_context, check_direct, FILE_FORMATS, user_agent
from ..data_classes import DomainItem
@@ -18,11 +19,8 @@ class BunkrCrawler():
ext = '.' + str(url).split('.')[-1]
if ext in FILE_FORMATS['Videos']:
url = URL(str(url).replace('https://cdn', 'https://media-files'))
- await domain_obj.add_to_album(link=url, referral=url, title="Bunkr Loose Files")
- return domain_obj
- else:
- await domain_obj.add_to_album(link=url, referral=url, title="Bunkr Loose Files")
- return domain_obj
+ await domain_obj.add_to_album(link=url, referral=url, title="Bunkr Loose Files")
+ return domain_obj
if "stream.bunkr." in url.host:
link = await self.stream(session, url)
@@ -70,8 +68,7 @@ class BunkrCrawler():
json_obj = json.loads(soup.select_one("script[id=__NEXT_DATA__]").text)
if not json_obj['props']['pageProps']:
raise Exception("Couldn't get link from HTML")
- else:
- link = URL(json_obj['props']['pageProps']['file']['mediafiles'] + '/' + json_obj['props']['pageProps']['file']['name'])
+ link = URL(json_obj['props']['pageProps']['file']['mediafiles'] + '/' + json_obj['props']['pageProps']['file']['name'])
return link
except Exception as e:
diff --git a/cyberdrop_dl/utils/crawlers/Coomer_Spider.py b/cyberdrop_dl/utils/crawlers/Coomer_Spider.py
index 7f47afc4e..90ed74542 100644
--- a/cyberdrop_dl/utils/crawlers/Coomer_Spider.py
+++ b/cyberdrop_dl/utils/crawlers/Coomer_Spider.py
@@ -1,6 +1,3 @@
-import asyncio
-import re
-
from bs4 import BeautifulSoup
from colorama import Fore
from yarl import URL
@@ -19,7 +16,7 @@ class CoomerCrawler:
results = []
if "thumbnail" in url.parts:
- parts = [x for x in url.parts if x != "thumbnail" and x != "/"]
+ parts = [x for x in url.parts if x not in ("thumbnail", "/")]
link = URL("https://coomer.party/" + "/".join(parts))
await domain_obj.add_to_album("Loose Coomer.Party Files", link, link)
elif "data" in url.parts:
@@ -87,4 +84,4 @@ class CoomerCrawler:
logger.debug("Error encountered while handling %s", str(url), exc_info=True)
await log("Error scraping " + str(url))
logger.debug(e)
- return []
\ No newline at end of file
+ return []
diff --git a/cyberdrop_dl/utils/crawlers/Gfycat_Spider.py b/cyberdrop_dl/utils/crawlers/Gfycat_Spider.py
index 799344999..426f15c93 100644
--- a/cyberdrop_dl/utils/crawlers/Gfycat_Spider.py
+++ b/cyberdrop_dl/utils/crawlers/Gfycat_Spider.py
@@ -1,7 +1,7 @@
from bs4 import BeautifulSoup
from yarl import URL
-from ..base_functions import logger, ssl_context
+from ..base_functions import log, logger, ssl_context
class GfycatCrawler():
diff --git a/cyberdrop_dl/utils/crawlers/Kemono_Spider.py b/cyberdrop_dl/utils/crawlers/Kemono_Spider.py
index 92fdfa0b2..1f6c3cee7 100644
--- a/cyberdrop_dl/utils/crawlers/Kemono_Spider.py
+++ b/cyberdrop_dl/utils/crawlers/Kemono_Spider.py
@@ -1,6 +1,3 @@
-import asyncio
-import re
-
from bs4 import BeautifulSoup
from colorama import Fore
from yarl import URL
@@ -19,7 +16,7 @@ class KemonoCrawler:
results = []
if "thumbnail" in url.parts:
- parts = [x for x in url.parts if x != "thumbnail" and x != "/"]
+ parts = [x for x in url.parts if x not in ("thumbnail", "/")]
link = URL("https://kemono.party/" + "/".join(parts))
await domain_obj.add_to_album("Loose Kemono.Party Files", link, link)
elif "data" in url.parts:
@@ -87,4 +84,4 @@ class KemonoCrawler:
logger.debug("Error encountered while handling %s", str(url), exc_info=True)
await log("Error scraping " + str(url))
logger.debug(e)
- return []
\ No newline at end of file
+ return []
diff --git a/cyberdrop_dl/utils/crawlers/Pixeldrain_Crawler.py b/cyberdrop_dl/utils/crawlers/Pixeldrain_Crawler.py
index 91736684d..dcfcce503 100644
--- a/cyberdrop_dl/utils/crawlers/Pixeldrain_Crawler.py
+++ b/cyberdrop_dl/utils/crawlers/Pixeldrain_Crawler.py
@@ -1,6 +1,5 @@
import json
-from bs4 import BeautifulSoup
from colorama import Fore
from yarl import URL
@@ -44,4 +43,4 @@ class PixelDrainCrawler:
await domain_obj.add_to_album("Loose Pixeldrain Files", link, url)
await log("Finished scrape of " + str(url), Fore.WHITE)
- return domain_obj
\ No newline at end of file
+ return domain_obj
diff --git a/cyberdrop_dl/utils/crawlers/Saint_Spider.py b/cyberdrop_dl/utils/crawlers/Saint_Spider.py
index 4f633a9e5..a584ed661 100644
--- a/cyberdrop_dl/utils/crawlers/Saint_Spider.py
+++ b/cyberdrop_dl/utils/crawlers/Saint_Spider.py
@@ -1,9 +1,8 @@
from bs4 import BeautifulSoup
from colorama import Fore
from yarl import URL
-import json
-from ..base_functions import log, logger, make_title_safe, ssl_context, check_direct
+from ..base_functions import log, logger, ssl_context
from ..data_classes import DomainItem
diff --git a/cyberdrop_dl/utils/crawlers/Thotsbay_Spider.py b/cyberdrop_dl/utils/crawlers/Thotsbay_Spider.py
index da093db29..b61c37945 100644
--- a/cyberdrop_dl/utils/crawlers/Thotsbay_Spider.py
+++ b/cyberdrop_dl/utils/crawlers/Thotsbay_Spider.py
@@ -47,14 +47,13 @@ class ThotsbayCrawler:
await self.login(session, url)
self.lock = 0
break
- else:
- await asyncio.sleep(2)
+ await asyncio.sleep(2)
else:
await log("login wasn't provided, consider using --thotsbay-username and --thotsbay-password")
await log("Not being logged in might cause issues.")
await self.parse_thread(session, url, Cascade, None)
except Exception as e:
- await log("there was an error signing into %s" % url.host)
+ await log(f"there was an error signing into {url.host}")
await log(e)
return
diff --git a/cyberdrop_dl/utils/data_classes.py b/cyberdrop_dl/utils/data_classes.py
index 39b5e67a8..f589ee896 100644
--- a/cyberdrop_dl/utils/data_classes.py
+++ b/cyberdrop_dl/utils/data_classes.py
@@ -12,9 +12,7 @@ class FileLock:
async def check_lock(self, filename):
await asyncio.sleep(.1)
- if filename.lower() in self.locked_files:
- return True
- return False
+ return filename.lower() in self.locked_files
async def add_lock(self, filename):
self.locked_files.append(filename.lower())
@@ -94,8 +92,8 @@ class CascadeItem:
self.domains[domain] = DomainItem(domain, {title: album})
async def is_empty(self):
- for domain_str, domain in self.domains.items():
- for album_str, album in domain.albums.items():
+ for _, domain in self.domains.items():
+ for _, album in domain.albums.items():
if album.link_pairs:
return False
return True
@@ -103,7 +101,7 @@ class CascadeItem:
async def append_title(self, title):
if not title:
return
- for domain_str, domain in self.domains.items():
+ for _, domain in self.domains.items():
new_albums = {}
for album_str, album in domain.albums.items():
new_title = title+'/'+album_str
@@ -119,17 +117,16 @@ class CascadeItem:
await self.add_album(domain_str, album_str, album)
async def dedupe(self):
- for domain_str, domain in self.domains.items():
- for album_str, album in domain.albums.items():
+ for _, domain in self.domains.items():
+ for _, album in domain.albums.items():
check = []
allowed = []
for pair in album.link_pairs:
- url, referrer = pair
+ url, _ = pair
if url in check:
continue
- else:
- check.append(url)
- allowed.append(pair)
+ check.append(url)
+ allowed.append(pair)
album.link_pairs = allowed
@@ -181,4 +178,3 @@ class SkipData:
self.sites['redgifs.com'] = True
if saint:
self.sites['saint.to'] = True
-
diff --git a/cyberdrop_dl/utils/downloaders.py b/cyberdrop_dl/utils/downloaders.py
index 164f4788c..5a5ad013b 100644
--- a/cyberdrop_dl/utils/downloaders.py
+++ b/cyberdrop_dl/utils/downloaders.py
@@ -22,7 +22,6 @@ from .rate_limiting import throttle
class FailureException(Exception):
"""Basic failure exception I can throw to force a retry."""
- pass
def retry(f):
@@ -34,7 +33,7 @@ def retry(f):
except FailureException:
if not self.disable_attempt_limit:
if self.current_attempt[str(args[0])] >= self.attempts - 1:
- logger.debug('Skipping %s...' % args[0])
+ logger.debug('Skipping %s...', args[0])
raise
logger.debug(f'Retrying ({self.current_attempt[str(args[0])]}) {args[0]}...')
self.current_attempt[str(args[0])] += 1
@@ -91,7 +90,7 @@ class Downloader:
show_progress: bool = True
) -> None:
"""Download the content of given URL"""
- if str(url) not in self.current_attempt.keys():
+ if str(url) not in self.current_attempt:
self.current_attempt[str(url)] = 0
headers = {'Referer': str(referral), 'user-agent': user_agent}
@@ -171,7 +170,7 @@ class Downloader:
if not download_name:
while True:
- filename = complete_file.stem + " (%d)" % iterations + ext
+ filename = f"{complete_file.stem} ({iterations}){ext}"
iterations += 1
temp_complete_file = (self.folder / self.title / filename)
if not temp_complete_file.exists():
@@ -188,7 +187,7 @@ class Downloader:
if temp_file.exists():
resume_point = temp_file.stat().st_size
- headers['Range'] = 'bytes=%d-' % resume_point
+ headers['Range'] = f'bytes={resume_point}-'
for key, value in self.delay.items():
if key in url.host:
@@ -197,7 +196,7 @@ class Downloader:
async with session.get(url, headers=headers, ssl=ssl_context, raise_for_status=True) as resp:
content_type = resp.headers.get('Content-Type')
if 'text' in content_type.lower() or 'html' in content_type.lower():
- logger.debug(f"Server for %s is either down or the file no longer exists" % str(url))
+ logger.debug("Server for %s is either down or the file no longer exists", str(url))
await self.File_Lock.remove_lock(original_filename)
return
@@ -230,13 +229,13 @@ class Downloader:
try:
logger.debug("Error status code: " + str(e.code))
if 400 <= e.code < 500 and e.code != 429:
- logger.debug("We ran into a 400 level error: %s" % str(e.code))
+ logger.debug("We ran into a 400 level error: %s", str(e.code))
if 'media-files.bunkr' in url.host:
pass
else:
return
resp.close()
- except Exception as e2:
+ except Exception:
pass
raise FailureException(e)
diff --git a/cyberdrop_dl/utils/rate_limiting.py b/cyberdrop_dl/utils/rate_limiting.py
index c8ccf0b7d..9afa53453 100644
--- a/cyberdrop_dl/utils/rate_limiting.py
+++ b/cyberdrop_dl/utils/rate_limiting.py
@@ -73,7 +73,7 @@ async def throttle(self, delay, host) -> None:
key: Optional[str] = None
while True:
if key is None:
- key = 'throttle:{}'.format(host)
+ key = f'throttle:{host}'
now = time.time()
last = self.throttle_times.get(key, 0.0)
elapsed = now - last
@@ -84,7 +84,6 @@ async def throttle(self, delay, host) -> None:
remaining = delay - elapsed + 0.25
- log_string = '\nDelaying request to %s for %.2f seconds.' % (
- host, remaining)
+ log_string = f'\nDelaying request to {host} for {remaining:.2f} seconds.'
logger.debug(log_string)
- await asyncio.sleep(remaining)
\ No newline at end of file
+ await asyncio.sleep(remaining)
diff --git a/cyberdrop_dl/utils/scraper_helper.py b/cyberdrop_dl/utils/scraper_helper.py
index ec162d9ab..7b765b88b 100644
--- a/cyberdrop_dl/utils/scraper_helper.py
+++ b/cyberdrop_dl/utils/scraper_helper.py
@@ -185,10 +185,9 @@ class ScrapeMapper():
if key in url_to_map.host:
if not self.skip_data.sites[key]:
await value(url=url_to_map, title=title)
- return
else:
await log("Skipping scrape of " + str(url_to_map))
- return
+ return
await log(str(url_to_map) + " is not supported currently.")
async with aiofiles.open("./Unsupported_Urls.txt", mode='a') as f:
await f.write(str(url_to_map)+"\n")
diff --git a/cyberdrop_dl/utils/sql_helper.py b/cyberdrop_dl/utils/sql_helper.py
index b50a684a5..cd7352f58 100644
--- a/cyberdrop_dl/utils/sql_helper.py
+++ b/cyberdrop_dl/utils/sql_helper.py
@@ -61,10 +61,7 @@ class SQLHelper:
return False
self.curs.execute("""SELECT completed FROM downloads WHERE path = ?""", (path, ))
sql_file_check = self.curs.fetchone()
- if sql_file_check:
- if sql_file_check[0] == 1:
- return True
- return False
+ return sql_file_check and sql_file_check[0] == 1
async def sql_insert_file(self, path, downloaded_filename, completed):
self.curs.execute("""INSERT OR IGNORE INTO downloads VALUES (?, ?, ?)""", (path, downloaded_filename, completed, ))
@@ -77,18 +74,14 @@ class SQLHelper:
async def check_filename(self, filename):
self.curs.execute("""SELECT EXISTS(SELECT 1 FROM downloads WHERE downloaded_filename = ?)""", (filename, ))
sql_check = self.curs.fetchone()[0]
- if sql_check == 1:
- return True
- else:
- return False
+ return sql_check == 1
async def get_download_filename(self, path):
self.curs.execute("""SELECT downloaded_filename FROM downloads WHERE path = ?""", (path, ))
filename = self.curs.fetchone()
if filename:
return filename[0]
- else:
- return None
+ return None
def exit_handler(self):
try: