Bulk asynchronous downloader for multiple file hosts
Python asynciobunkrcyberdropdownloaderdropboxfilestergofilegoogle-drivemediafiremegamega-nzonedrivepatreonpawchivepinterestpixeldraintransfer-ittwitchtwittervk
feat: add missav support (#807)
NTFSvolume1456e80a1820
diff --git a/cyberdrop_dl/crawlers/__init__.py b/cyberdrop_dl/crawlers/__init__.pyindex 2a341f474..dbaa10104 100644--- a/cyberdrop_dl/crawlers/__init__.py+++ b/cyberdrop_dl/crawlers/__init__.py@@ -36,6 +36,7 @@ from .imgur import ImgurCrawlerfrom .kemono import KemonoCrawlerfrom .luscious import LusciousCrawlerfrom .mediafire import MediaFireCrawler+from .missav import MissAVCrawlerfrom .motherless import MotherlessCrawlerfrom .nekohouse import NekohouseCrawlerfrom .nhentai import NHentaiCrawlerdiff --git a/cyberdrop_dl/crawlers/missav.py b/cyberdrop_dl/crawlers/missav.pynew file mode 100644index 000000000..a4055fdbc--- /dev/null+++ b/cyberdrop_dl/crawlers/missav.py@@ -0,0 +1,142 @@+from __future__ import annotations++import calendar+from datetime import datetime+from pathlib import Path+from typing import TYPE_CHECKING, NamedTuple++from yarl import URL++from cyberdrop_dl.clients.errors import ScrapeError+from cyberdrop_dl.crawlers.crawler import Crawler, create_task_id+from cyberdrop_dl.utils.utilities import error_handling_wrapper++if TYPE_CHECKING:+ from collections.abc import Generator++ from bs4 import BeautifulSoup++ from cyberdrop_dl.managers.manager import Manager+ from cyberdrop_dl.utils.data_enums_classes.url_objects import ScrapeItem+++M3U8_SERVER = URL("https://surrit.com/")+TITLE_SELECTOR = "meta [property='og:title']"++DATE_SELECTOR = "div > span:contains('Release date:') + time"+DVD_CODE_SELECTOR = "div > span:contains('Code:') + span"+++class Format(NamedTuple):+ height: int+ width: int+++class MissAVCrawler(Crawler):+ primary_base_domain = URL("https://missav.ws")++ def __init__(self, manager: Manager, _=None) -> None:+ super().__init__(manager, "missav", "MissAV")++ """~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"""++ @create_task_id+ async def fetch(self, scrape_item: ScrapeItem) -> None:+ """Determines where to send the scrape item based on the url."""+ return await self.video(scrape_item)++ @error_handling_wrapper+ async def video(self, scrape_item: ScrapeItem) -> None:+ canonical_url = self.primary_base_domain / "en" / scrape_item.url.name+ scrape_item.url = canonical_url+ if await self.check_complete_from_referer(canonical_url):+ return++ async with self.request_limiter:+ soup: BeautifulSoup = await self.client.get_soup_cffi(self.domain, scrape_item.url)++ title = clean_title = soup.select_one(TITLE_SELECTOR)["content"].strip() # type: ignore+ date_tag = soup.select_one(DATE_SELECTOR)+ dvd_code_tag = soup.select_one(DVD_CODE_SELECTOR)++ date_str: str = date_tag.get("datetime") if date_tag else "" # type: ignore+ dvd_code = dvd_code_tag.text.strip().upper() if dvd_code_tag else None++ if dvd_code:+ clean_title = clean_title.replace(dvd_code.lower(), "").replace(dvd_code.upper(), "").strip()+ title = f"{dvd_code} {clean_title}"++ if date_str:+ date = parse_datetime(date_str)+ scrape_item.possible_datetime = date++ uuid = get_uuid(soup)+ del soup+ m3u8_playlist_url = M3U8_SERVER / uuid / "playlist.m3u8"++ async with self.request_limiter:+ m3u8_playlist_content: str = await self.client.get_text(self.domain, m3u8_playlist_url)++ playlist_name, resolution = get_best_resolution(m3u8_playlist_content)+ m3u8_video_url = M3U8_SERVER / uuid / playlist_name+ video_part_base_url = m3u8_video_url.parent++ async with self.request_limiter:+ m3u8_video_content: str = await self.client.get_text(self.domain, m3u8_video_url)++ title = Path(title).as_posix().replace("/", "-") # remove OS separators+ filename = f"{title} [{resolution}].mp4"+ filename, ext = self.get_filename_and_ext(filename)++ await self.handle_file(+ m3u8_playlist_url,+ scrape_item,+ filename,+ ext,+ m3u8_content=m3u8_video_content,+ debrid_link=video_part_base_url,+ )+++def get_best_resolution(m3u8_playlist_content: str) -> tuple[str, str]:+ resolutions = get_available_formats(m3u8_playlist_content)+ best_resolution = max(resolutions)+ name = get_playlist_name(m3u8_playlist_content, best_resolution)+ return name, f"{best_resolution.height}p"+++def get_available_formats(m3u8_playlist_content: str) -> Generator[Format]:+ for line in m3u8_playlist_content.splitlines():+ if "RESOLUTION=" not in line:+ continue+ dimentions = line.split("RESOLUTION=")[-1].strip().split("x")+ yield Format(*map(int, reversed(dimentions)))+++def get_playlist_name(m3u8_playlist_content: str, res: Format) -> str:+ format_str = f"{res.width}x{res.height}"+ get_next = False+ for line in m3u8_playlist_content.splitlines():+ if get_next:+ return line.strip()+ if f"RESOLUTION={format_str}" in line:+ get_next = True++ raise ScrapeError(422)+++def get_uuid(soup: BeautifulSoup) -> str:+ info_js_script = soup.select_one("script:contains('m3u8|')")+ js_text = info_js_script.text if info_js_script else None+ if not js_text:+ raise ScrapeError(422)++ uuid_joined_parts = js_text.split("m3u8|", 1)[-1].split("|com|surrit", 1)[0]+ uuid_parts = reversed(uuid_joined_parts.split("|"))+ return "-".join(uuid_parts)+++def parse_datetime(date: str) -> int:+ """Parses a datetime string into a unix timestamp."""+ parsed_date = datetime.fromisoformat(date)+ return calendar.timegm(parsed_date.timetuple())diff --git a/cyberdrop_dl/downloader/downloader.py b/cyberdrop_dl/downloader/downloader.pyindex 1eed30587..ab3a3d161 100644--- a/cyberdrop_dl/downloader/downloader.py+++ b/cyberdrop_dl/downloader/downloader.py@@ -176,7 +176,7 @@ class Downloader:# reference=media_item,# skip_hashing=True,)- seg_media_items.append(media_item)+ seg_media_items.append(seg_media_item)return self.run(seg_media_item)self.update_queued_files()diff --git a/cyberdrop_dl/managers/manager.py b/cyberdrop_dl/managers/manager.pyindex 5c2c5f367..a83ac10c1 100644--- a/cyberdrop_dl/managers/manager.py+++ b/cyberdrop_dl/managers/manager.py@@ -24,7 +24,7 @@ from cyberdrop_dl.managers.storage_manager import StorageManagerfrom cyberdrop_dl.ui.textual import TextualUIfrom cyberdrop_dl.utils import constantsfrom cyberdrop_dl.utils.args import ParsedArgs-from cyberdrop_dl.utils.ffmpeg import FFmpeg+from cyberdrop_dl.utils.ffmpeg import FFmpeg, get_ffmpeg_versionfrom cyberdrop_dl.utils.logger import QueuedLogger, logfrom cyberdrop_dl.utils.transfer import transfer_v5_db_to_v6@@ -266,6 +266,7 @@ class Manager:log(f"Using Authentication: \n{json.dumps(auth_provided, indent=4, sort_keys=True)}")log(f"Using Settings: \n{config_settings}")log(f"Using Global Settings: \n{global_settings}")+ log(f"Using FFmpeg version: {get_ffmpeg_version()}")async def async_db_close(self) -> None:"Partial shutdown for managers used for hash directory scanner"diff --git a/cyberdrop_dl/utils/ffmpeg.py b/cyberdrop_dl/utils/ffmpeg.pyindex 06917e99c..f44359ac7 100644--- a/cyberdrop_dl/utils/ffmpeg.py+++ b/cyberdrop_dl/utils/ffmpeg.py@@ -1,6 +1,7 @@from __future__ import annotationsimport asyncio+import shutilimport subprocessfrom datetime import datetimefrom functools import lru_cache@@ -19,7 +20,7 @@ if TYPE_CHECKING:FFMPEG_CALL_PREFIX = "ffmpeg", "-y", "-loglevel", "error"CONCAT_INPUT_ARGS = "-f", "concat", "-safe", "0", "-i"-CODEC_COPY = "-c", "-copy"+CODEC_COPY = "-c", "copy"class SubProcessResult(NamedTuple):@@ -41,7 +42,7 @@ class FFmpeg:self.version = get_ffmpeg_version()self.is_available = bool(self.version)- async def concat(self, *input_files: Path, output_file: Path) -> SubProcessResult:+ async def concat(self, *input_files: Path, output_file: Path, same_folder: bool = True) -> SubProcessResult:if not self.is_available:raise RuntimeError("ffmpeg is not available")now = datetime.now().strftime("%Y%m%d_%H%M%S")@@ -50,7 +51,11 @@ class FFmpeg:await _create_concat_input_file(*input_files, file_path=concat_file_path)result = await _concat(concat_file_path, output_file)if result.success:- await async_delete_files(concat_file_path, *input_files)+ if same_folder:+ folder = input_files[0].parent+ await asyncio.to_thread(shutil.rmtree, folder, True)+ else:+ await async_delete_files(concat_file_path, *input_files)return resultdiff --git a/cyberdrop_dl/utils/utilities.py b/cyberdrop_dl/utils/utilities.pyindex eafcba161..2400f94e1 100644--- a/cyberdrop_dl/utils/utilities.py+++ b/cyberdrop_dl/utils/utilities.py@@ -57,8 +57,6 @@ def error_handling_wrapper(func: Callable) -> Callable:@wraps(func)async def wrapper(self: Crawler | Downloader, *args, **kwargs):item: ScrapeItem | MediaItem | URL = args[0]- if getattr(item, "is_segment", False):- returnlink: URL = item if isinstance(item, URL) else item.urlorigin = exc_info = Nonelink_to_show: URL | str = ""@@ -80,6 +78,9 @@ def error_handling_wrapper(func: Callable) -> Callable:exc_info = eerror_log_msg = ErrorLogMessage.from_unknown_exc(e)+ if getattr(item, "is_segment", False):+ return+link_to_show = link_to_show or linkorigin = origin or get_origin(item)log_prefix = getattr(self, "log_prefix", None)