Skip to content

Bulk asynchronous downloader for multiple file hosts

Cleanup base_functions.py

Arkadiy Illarionov2ca4fce65d29
diff --git a/cyberdrop_dl/base_functions/base_functions.py b/cyberdrop_dl/base_functions/base_functions.py
index 49821120a..7b6cc4d32 100644
--- a/cyberdrop_dl/base_functions/base_functions.py
+++ b/cyberdrop_dl/base_functions/base_functions.py
@@ -3,15 +3,10 @@ from __future__ import annotations
import logging
import os
import re
-import shutil
-from http import HTTPStatus
-from pathlib import Path
-import aiofiles
import rich
from yarl import URL
-from cyberdrop_dl.base_functions.data_classes import MediaItem
from cyberdrop_dl.base_functions.error_classes import NoExtensionFailure
FILE_FORMATS = {
@@ -49,46 +44,6 @@ async def log(text, quiet=False) -> None:
rich.print(str(text))
-async def regex_links(urls: list) -> list:
- """Regex grab the links from the URLs.txt file"""
- """This allows code blocks or full paragraphs to be copy and pasted into the URLs.txt"""
- yarl_links = []
- for line in urls:
- if line.lstrip().startswith('#'):
- continue
-
- all_links = [x.group().replace(".md.", ".") for x in re.finditer(
- r"(?:http.*?)(?=($|\n|\r\n|\r|\s|\"|\[/URL]|]\[|\[/img]))", line)]
- for link in all_links:
- yarl_links.append(URL(link))
- return yarl_links
-
-
-async def check_free_space(required_space_gb: int, download_directory: Path) -> bool:
- """Checks if there is enough free space on the drive to continue operating"""
- free_space = shutil.disk_usage(download_directory.parent).free
- free_space_gb = free_space / 1024 ** 3
- return free_space_gb >= required_space_gb
-
-
-async def allowed_filetype(media: MediaItem, block_images: bool, block_video: bool, block_audio: bool, block_other: bool):
- """Checks whether the enclosed file is allowed to be downloaded"""
- ext = media.ext
- if block_images:
- if ext in FILE_FORMATS["Images"]:
- return False
- if block_video:
- if ext in FILE_FORMATS["Videos"]:
- return False
- if block_audio:
- if ext in FILE_FORMATS["Audio"]:
- return False
- if block_other:
- if ext not in FILE_FORMATS["Images"] and ext not in FILE_FORMATS["Videos"] and ext not in FILE_FORMATS["Audio"]:
- return False
- return True
-
-
async def purge_dir(dirname) -> None:
"""Purges empty directories"""
deleted = []
@@ -102,13 +57,6 @@ async def purge_dir(dirname) -> None:
list(map(os.rmdir, deleted))
-async def write_last_post_file(file: Path, url: str):
- """Writes the last post url from a thread to the specified file"""
- async with aiofiles.open(file, mode='a') as f:
- await f.write(url + '\n')
- return
-
-
async def get_db_path(url: URL, referer=None):
"""Gets the URL path to be put into the DB and checked from the DB"""
url_path = url.path
@@ -157,8 +105,3 @@ async def get_filename_and_ext(filename, forum=False):
ext = "." + filename_parts[-1].lower()
filename = await sanitize(filename_parts[0] + ext)
return filename, ext
-
-
-async def is_4xx_client_error(status_code: int) -> bool:
- """Checks whether the HTTP status code is 4xx client error"""
- return HTTPStatus.BAD_REQUEST <= status_code < HTTPStatus.INTERNAL_SERVER_ERROR
diff --git a/cyberdrop_dl/crawlers/Xenforo_Spider.py b/cyberdrop_dl/crawlers/Xenforo_Spider.py
index 5510e8355..782f67028 100644
--- a/cyberdrop_dl/crawlers/Xenforo_Spider.py
+++ b/cyberdrop_dl/crawlers/Xenforo_Spider.py
@@ -2,17 +2,30 @@ from __future__ import annotations
import asyncio
import re
+from pathlib import Path
+import aiofiles
from bs4 import BeautifulSoup
from yarl import URL
-from ..base_functions.base_functions import log, make_title_safe, write_last_post_file, get_filename_and_ext, logger
+from ..base_functions.base_functions import (
+ get_filename_and_ext,
+ log,
+ logger,
+ make_title_safe,
+)
from ..base_functions.data_classes import CascadeItem, MediaItem
from ..base_functions.error_classes import FailedLoginFailure, NoExtensionFailure
from ..base_functions.sql_helper import SQLHelper
from ..client.client import ScrapeSession
+async def write_last_post_file(file: Path, url: str):
+ """Writes the last post url from a thread to the specified file"""
+ async with aiofiles.open(file, mode='a') as f:
+ await f.write(url + '\n')
+
+
class ForumLogin:
def __init__(self, name: str, username: str, password: str):
self.name = name
diff --git a/cyberdrop_dl/downloader/downloader_utils.py b/cyberdrop_dl/downloader/downloader_utils.py
new file mode 100644
index 000000000..d7606d4a7
--- /dev/null
+++ b/cyberdrop_dl/downloader/downloader_utils.py
@@ -0,0 +1,42 @@
+import shutil
+from base64 import b64encode
+from http import HTTPStatus
+from pathlib import Path
+
+from cyberdrop_dl.base_functions.base_functions import FILE_FORMATS
+from cyberdrop_dl.base_functions.data_classes import MediaItem
+
+
+async def allowed_filetype(media: MediaItem, block_images: bool, block_video: bool, block_audio: bool, block_other: bool):
+ """Checks whether the enclosed file is allowed to be downloaded"""
+ ext = media.ext
+ if block_images:
+ if ext in FILE_FORMATS["Images"]:
+ return False
+ if block_video:
+ if ext in FILE_FORMATS["Videos"]:
+ return False
+ if block_audio:
+ if ext in FILE_FORMATS["Audio"]:
+ return False
+ if block_other:
+ if ext not in FILE_FORMATS["Images"] and ext not in FILE_FORMATS["Videos"] and ext not in FILE_FORMATS["Audio"]:
+ return False
+ return True
+
+
+async def basic_auth(username, password):
+ token = b64encode(f"{username}:{password}".encode('utf-8')).decode("ascii")
+ return f'Basic {token}'
+
+
+async def check_free_space(required_space_gb: int, download_directory: Path) -> bool:
+ """Checks if there is enough free space on the drive to continue operating"""
+ free_space = shutil.disk_usage(download_directory.parent).free
+ free_space_gb = free_space / 1024 ** 3
+ return free_space_gb >= required_space_gb
+
+
+async def is_4xx_client_error(status_code: int) -> bool:
+ """Checks whether the HTTP status code is 4xx client error"""
+ return HTTPStatus.BAD_REQUEST <= status_code < HTTPStatus.INTERNAL_SERVER_ERROR
diff --git a/cyberdrop_dl/downloader/downloaders.py b/cyberdrop_dl/downloader/downloaders.py
index 31d6e0e9c..d783fd5ea 100644
--- a/cyberdrop_dl/downloader/downloaders.py
+++ b/cyberdrop_dl/downloader/downloaders.py
@@ -3,7 +3,6 @@ from __future__ import annotations
import asyncio
import logging
import multiprocessing
-from base64 import b64encode
from functools import wraps
from http import HTTPStatus
from random import gauss
@@ -14,14 +13,9 @@ from rich.live import Live
from rich.progress import TaskID
from yarl import URL
-from .progress_definitions import get_forum_table, cascade_progress, domain_progress, album_progress, file_progress, \
- forum_progress, get_cascade_table, overall_file_progress
from cyberdrop_dl.base_functions.base_functions import (
- allowed_filetype,
- check_free_space,
clear,
get_db_path,
- is_4xx_client_error,
log,
logger,
)
@@ -31,10 +25,22 @@ from cyberdrop_dl.base_functions.sql_helper import SQLHelper
from cyberdrop_dl.client.client import Client, DownloadSession
from cyberdrop_dl.scraper.Scraper import ScrapeMapper
-
-async def basic_auth(username, password):
- token = b64encode(f"{username}:{password}".encode('utf-8')).decode("ascii")
- return f'Basic {token}'
+from .downloader_utils import (
+ allowed_filetype,
+ basic_auth,
+ check_free_space,
+ is_4xx_client_error,
+)
+from .progress_definitions import (
+ album_progress,
+ cascade_progress,
+ domain_progress,
+ file_progress,
+ forum_progress,
+ get_cascade_table,
+ get_forum_table,
+ overall_file_progress,
+)
def retry(f):
diff --git a/cyberdrop_dl/downloader/old_downloaders.py b/cyberdrop_dl/downloader/old_downloaders.py
index 56a98d93a..d2d9fd9a6 100644
--- a/cyberdrop_dl/downloader/old_downloaders.py
+++ b/cyberdrop_dl/downloader/old_downloaders.py
@@ -3,7 +3,6 @@ from __future__ import annotations
import asyncio
import logging
import multiprocessing
-from base64 import b64encode
from functools import wraps
from http import HTTPStatus
from random import gauss
@@ -14,11 +13,8 @@ from tqdm import tqdm
from yarl import URL
from cyberdrop_dl.base_functions.base_functions import (
- allowed_filetype,
- check_free_space,
clear,
get_db_path,
- is_4xx_client_error,
log,
logger,
)
@@ -28,10 +24,12 @@ from cyberdrop_dl.base_functions.sql_helper import SQLHelper
from cyberdrop_dl.client.client import Client, DownloadSession
from cyberdrop_dl.scraper.Scraper import ScrapeMapper
-
-async def basic_auth(username, password):
- token = b64encode(f"{username}:{password}".encode('utf-8')).decode("ascii")
- return f'Basic {token}'
+from .downloader_utils import (
+ allowed_filetype,
+ basic_auth,
+ check_free_space,
+ is_4xx_client_error,
+)
def retry(f):
diff --git a/cyberdrop_dl/main.py b/cyberdrop_dl/main.py
index 341f0c3e9..e919cd33e 100644
--- a/cyberdrop_dl/main.py
+++ b/cyberdrop_dl/main.py
@@ -6,11 +6,12 @@ from pathlib import Path
import aiofiles
from yarl import URL
-from cyberdrop_dl.base_functions.base_functions import log, clear, regex_links, check_free_space, purge_dir
+from cyberdrop_dl.base_functions.base_functions import clear, log, purge_dir
from cyberdrop_dl.base_functions.config_manager import run_args, document_args
from cyberdrop_dl.base_functions.sorting_functions import Sorter
from cyberdrop_dl.base_functions.sql_helper import SQLHelper
from cyberdrop_dl.client.client import Client
+from cyberdrop_dl.downloader.downloader_utils import check_free_space
from cyberdrop_dl.downloader.downloaders import download_cascade, download_forums
from cyberdrop_dl.downloader.old_downloaders import old_download_cascade, old_download_forums
from cyberdrop_dl.scraper.Scraper import ScrapeMapper
@@ -136,6 +137,21 @@ async def file_management(args: dict, links: list) -> None:
await f.write("URL,REFERER,REASON\n")
+async def regex_links(urls: list) -> list:
+ """Regex grab the links from the URLs.txt file"""
+ """This allows code blocks or full paragraphs to be copy and pasted into the URLs.txt"""
+ yarl_links = []
+ for line in urls:
+ if line.lstrip().startswith('#'):
+ continue
+
+ all_links = [x.group().replace(".md.", ".") for x in re.finditer(
+ r"(?:http.*?)(?=($|\n|\r\n|\r|\s|\"|\[/URL]|]\[|\[/img]))", line)]
+ for link in all_links:
+ yarl_links.append(URL(link))
+ return yarl_links
+
+
async def consolidate_links(args: dict, links: list) -> list:
"""We consolidate links from command line and from URLs.txt into a singular list"""
links = list(map(URL, links))