Bulk asynchronous downloader for multiple file hosts
Python asynciobunkrcyberdropdownloaderdropboxfilestergofilegoogle-drivemediafiremegamega-nzonedrivepatreonpawchivepinterestpixeldraintransfer-ittwitchtwittervk
feat: support multi stream downloads (#2117)
NTFSvolume1fd23e1444cc
diff --git a/cyberdrop_dl/clients/downloads.py b/cyberdrop_dl/clients/downloads.pyindex 6a6bd3110..a82e8408b 100644--- a/cyberdrop_dl/clients/downloads.py+++ b/cyberdrop_dl/clients/downloads.py@@ -6,16 +6,15 @@ import loggingimport timefrom contextvars import ContextVarfrom http import HTTPStatus-from typing import TYPE_CHECKING, Any, final+from typing import TYPE_CHECKING, Any, ClassVar, finalfrom aiohttp import hdrsfrom cyberdrop_dl import aio, constants, ffmpeg, storagefrom cyberdrop_dl.clients import etagfrom cyberdrop_dl.clients.http import JSON_CHECK, check_http_status-from cyberdrop_dl.constants import FileExt, HashMode+from cyberdrop_dl.constants import FileExtfrom cyberdrop_dl.exceptions import DownloadError, InvalidContentTypeError, SlowDownloadError-from cyberdrop_dl.hasher import compute_in_place_hashfrom cyberdrop_dl.signature import simple_reprfrom cyberdrop_dl.utils import dates, enter_context@@ -43,11 +42,12 @@ _SLOW_DOWNLOAD_PERIOD: int = 10 # secondsclass DownloadClient:"""Low level class that performs the actual HTTP download operations."""+ SUPPORTS_RANGES: ClassVar[bool] = True+def __init__(self, manager: Manager) -> None:self.manager = managerself.config = self.manager.configself.download_speed_threshold = self.config.downloads.slow_speed- self._supports_ranges: bool = Truespeed_limit = self.config.downloads.speed_limitself.speed_limiter = aio.RateLimiter(speed_limit, time_period=1)@@ -77,7 +77,8 @@ class DownloadClient:media_item.partial_file = media_item.download_folder / f"{name}{constants.TempExt.PART}"resume_point = 0- if self._supports_ranges and media_item.partial_file and (size := await aio.get_size(media_item.partial_file)):+ media_item.headers.pop(hdrs.RANGE, None) # Delete ranges from previous attempts+ if self.SUPPORTS_RANGES and media_item.partial_file and (size := await aio.get_size(media_item.partial_file)):resume_point = sizemedia_item.headers[hdrs.RANGE] = f"bytes={size}-"@@ -102,8 +103,7 @@ class DownloadClient:return Truelogger.info(f"Skipping {media_item.url} as it has already been downloaded")self.manager.scrape_mapper.tui.files.stats.prev_completed += 1- await self.process_completed(media_item, domain)- await self.handle_media_item_completion(media_item, downloaded=False)+ await self.mark_completed(media_item, domain)return Falsereturn None@@ -131,7 +131,7 @@ class DownloadClient:return Truedef _make_hook(self, media_item: MediaItem, resume_point: int) -> ProgressHook:- if media_item.is_segment:+ if media_item.is_segment and not media_item.extra_info.get("MUX_STREAM"):return self.manager.scrape_mapper.tui.downloads.download_hls_seg()size = (media_item.size + resume_point) if media_item.size is not None else None@@ -191,7 +191,7 @@ class DownloadClient:logger.info(f"Download removed {media_item.url} due to mark completed option")self.manager.scrape_mapper.tui.files.stats.skipped += 1# set completed path- await self.process_completed(media_item, domain)+ await self.mark_completed(media_item, domain)return Falsedownloaded = await self._download(domain, media_item)@@ -204,31 +204,14 @@ class DownloadClient:returnawait self.manager.database.history.insert_incompleted(domain, media_item)- async def process_completed(self, media_item: MediaItem, domain: str) -> None:- await self.mark_completed(domain, media_item)- await self.add_file_size(domain, media_item)-- async def mark_completed(self, domain: str, media_item: MediaItem) -> None:+ async def mark_completed(self, media_item: MediaItem, domain: str) -> None:await self.manager.database.history.mark_complete(domain, media_item)-- async def add_file_size(self, domain: str, media_item: MediaItem) -> None:if not media_item.path:media_item.path = media_item.download_folder / media_item.filename+if await aio.is_file(media_item.path):await self.manager.database.history.add_filesize(domain, media_item)- async def handle_media_item_completion(self, media_item: MediaItem, *, downloaded: bool = False) -> None:- """Sends to hash client to handle hashing and marks as completed/current download."""- media_item.downloaded = downloaded- try:- if media_item.is_segment or self.config.hashing.mode != HashMode.IN_PLACE:- return- await compute_in_place_hash(self.manager.hasher, media_item)- except Exception:- logger.exception(f"Unable to compute hashes of: {media_item.path}")- finally:- self.manager.add_completed(media_item)-async def get_final_file_info(self, media_item: MediaItem, domain: str) -> tuple[bool, bool]: # noqa: C901, PLR0912, PLR0915"""Complicated checker for if a file already exists, and was already downloaded."""if not media_item.path:diff --git a/cyberdrop_dl/crawlers/crawler.py b/cyberdrop_dl/crawlers/crawler.pyindex 48d87755f..5b815622f 100644--- a/cyberdrop_dl/crawlers/crawler.py+++ b/cyberdrop_dl/crawlers/crawler.py@@ -26,7 +26,7 @@ from cyberdrop_dl.exceptions import MaxChildrenError, NoExtensionError, ScrapeErfrom cyberdrop_dl.filepath import check_dangerous_filename, check_path_traversal, compose_filename, get_filename_and_extfrom cyberdrop_dl.mediaprops import ISO639Subtitle, Resolutionfrom cyberdrop_dl.models.validators import strings-from cyberdrop_dl.url_objects import AbsoluteHttpURL, MediaItem, ScrapeItem, is_absolute_http_url+from cyberdrop_dl.url_objects import AbsoluteHttpURL, MediaItem, MuxVideo, ScrapeItem, is_absolute_http_urlfrom cyberdrop_dl.utils import css, dates, enter_context, fast_cache, is_blob_or_svg, m3u8, parse_url, uniquefrom cyberdrop_dl.utils._url import matches_any_host, remove_trailing_slashfrom cyberdrop_dl.utils.dataclass import ConfigDataclass, DictDataclass, frozen@@ -240,7 +240,7 @@ class Crawler(HTTPMixin, HLSMixin, ABC):self.downloader: Downloader = Downloader(manager,use_server_lock=self.__dl_config__.server_lock,- _slots=self.__dl_config__.slots,+ slots=self.__dl_config__.slots,)self.__http_ctx__: HTTPContext = HTTPContext.build(self.DOMAIN, self.__http_config__, self.__throttle)@@ -522,7 +522,7 @@ class Crawler(HTTPMixin, HLSMixin, ABC):*,custom_filename: str | None = None,debrid_link: DebridURL = None,- m3u8: m3u8.Rendition | None = None,+ m3u8: m3u8.Rendition | MuxVideo | None = None,metadata: object = None,referer: AbsoluteHttpURL | None = None,frag: str | None = None,@@ -601,17 +601,17 @@ class Crawler(HTTPMixin, HLSMixin, ABC):}@final- async def _download(self, media_item: MediaItem, m3u8: m3u8.Rendition | None, *, skip: bool = False) -> None:+ async def _download(+ self, media_item: MediaItem, streams: m3u8.Rendition | MuxVideo | None, *, skip: bool = False+ ) -> None:if self.__dl_config__.impersonate is not None:media_item.extra_info["impersonate"] = self.__dl_config__.impersonatetry:if skip or SKIP_DOWNLOAD.get():return- if m3u8:- await self.downloader.download_hls(media_item, m3u8)- else:- await self.downloader.run(media_item)++ await self.downloader.run(media_item, streams)finally:await self.__write_to_jsonl(media_item)@@ -642,14 +642,14 @@ class Crawler(HTTPMixin, HLSMixin, ABC):return downloaded- async def handle_media_item(self, media_item: MediaItem, m3u8: m3u8.Rendition | None = None) -> None:+ async def handle_media_item(self, media_item: MediaItem, streams: m3u8.Rendition | MuxVideo | None = None) -> None:with (enter_context(IGNORE_CONTENT_TYPE, True)if self.__dl_config__.ignore_content_typeelse contextlib.nullcontext()):self._task_mngr.downloads.create_task(- self._download(media_item, m3u8, skip=await self.__should_skip(media_item))+ self._download(media_item, streams, skip=await self.__should_skip(media_item)))async def __should_skip(self, media_item: MediaItem) -> bool:diff --git a/cyberdrop_dl/downloader/hls.py b/cyberdrop_dl/downloader/hls.pyindex 0673188f7..985df4f15 100644--- a/cyberdrop_dl/downloader/hls.py+++ b/cyberdrop_dl/downloader/hls.py@@ -2,6 +2,7 @@ from __future__ import annotationsimport asyncioimport dataclasses+import itertoolsimport loggingfrom contextvars import ContextVarfrom http import HTTPStatus@@ -9,7 +10,6 @@ from typing import TYPE_CHECKING, NamedTuple, Protocolfrom cyberdrop_dl import aio, constants, ffmpegfrom cyberdrop_dl.exceptions import DownloadError-from cyberdrop_dl.url_objects import AbsoluteHttpURL, MediaItemfrom cyberdrop_dl.utils import parse_urlfrom cyberdrop_dl.utils.crypto import aes_cbc_decrypt, aes_unpadfrom cyberdrop_dl.utils.m3u8 import HLSKey@@ -21,19 +21,16 @@ if TYPE_CHECKING:from m3u8.model import InitializationSection, Segmentfrom cyberdrop_dl.clients.http import HTTPClient+ from cyberdrop_dl.url_objects import AbsoluteHttpURL, MediaItemfrom cyberdrop_dl.utils.m3u8 import M3U8, RenditionDownloadFn = Callable[[MediaItem], Awaitable[bool]]-CONCURRENT_SEGMENTS: ContextVar[int] = ContextVar("CONCURRENT_SEGMENTS")-_DECRYPTER: ContextVar[AESHLSDecrypter] = ContextVar("_DECRYPTER")logger = logging.getLogger(__name__)--class SegmentDownloadResult(NamedTuple):- item: MediaItem- downloaded: bool+CONCURRENT_SEGMENTS: ContextVar[int] = ContextVar("CONCURRENT_SEGMENTS")+_DECRYPTER: ContextVar[AESHLSDecrypter] = ContextVar("_DECRYPTER")class Streams(NamedTuple):@@ -77,8 +74,8 @@ class AESHLSDecrypter(HLSDecrypter):return aes_unpad(aes_cbc_decrypt(content, aes_key, key.iv))-def _parse_segments(segments: Sequence[Segment | InitializationSection]) -> Generator[HLSSegment]:- padding = max(5, len(str(len(segments))))+def _create_segments(segments: Iterable[Segment | InitializationSection], count: int) -> Generator[HLSSegment]:+ padding = max(5, len(str(count)))for index, segment in enumerate(segments, 1):assert segment.uriyield HLSSegment(@@ -89,75 +86,60 @@ def _parse_segments(segments: Sequence[Segment | InitializationSection]) -> Gene)-def _create_media_segments(- media_item: MediaItem,- segments: Iterable[HLSSegment],- download_folder: Path,-) -> Generator[MediaItem]:- for segment in segments:- # TODO: segments download should bypass the downloads slots limits.- # They count as a single download-- seg_media_item = MediaItem(- url=segment.url,- domain=media_item.domain,- download_folder=download_folder,- filename=segment.name,- db_path=media_item.db_path,- referer=media_item.url,- album_id=media_item.album_id,- ext=media_item.ext,- parents=media_item.parents,- uploaded_at=media_item.uploaded_at,- is_segment=True,- )- seg_media_item.headers = media_item.headers.copy()- if segment.decrypt_info:- segment.decrypt_info(seg_media_item.extra_info)+def _create_media_segment(media_item: MediaItem, segment: HLSSegment, download_folder: Path) -> MediaItem:+ # TODO: segments download should bypass the downloads slots limits.+ # They count as a single download++ new_item = media_item.as_segment(segment.name, segment.url)+ new_item.download_folder = download_folder+ if segment.decrypt_info:+ segment.decrypt_info(new_item.extra_info)++ return new_item- yield seg_media_item++def _create_media_segments(m3u8: M3U8, temp_dir: Path, item: MediaItem) -> Generator[MediaItem]:+ assert m3u8.media_type+ out_folder = temp_dir / m3u8.media_type+ for segment in _create_segments(itertools.chain(m3u8.segment_map, m3u8.segments), count=m3u8.total_segments):+ yield _create_media_segment(item, segment, out_folder)-def _segments(m3u8: M3U8) -> list[Segment | InitializationSection]:- segments = m3u8.segment_map + m3u8.segments- if not segments:+def _check_segments(m3u8: M3U8) -> None:+ if m3u8.total_segments == 0:msg = f"{m3u8.media_type} m3u8 manifest ({m3u8.source}) has no valid segments"raise DownloadError(HTTPStatus.NO_CONTENT, msg)- return segmentsasync def _download_m3u8(m3u8: M3U8,temp_dir: Path,- media_item: MediaItem,+ item: MediaItem,download_fn: DownloadFn,sem: asyncio.BoundedSemaphore,) -> Path:assert m3u8.media_type- segments = _segments(m3u8)- output = _prepare_output_path(m3u8, media_item.path)+ _check_segments(m3u8)+ output = _prepare_output_path(m3u8, item.path)if await aio.is_file(output):return output- async def download(seg_media_item: MediaItem) -> SegmentDownloadResult:- return SegmentDownloadResult(seg_media_item, await download_fn(seg_media_item))-- m_segments = _create_media_segments(- media_item,- _parse_segments(segments),- download_folder=temp_dir / m3u8.media_type,- )-logger.debug("Starting HLS download (%s, %s segments) for %s (%s)",m3u8.media_type,- f"{len(segments):,}",- media_item.real_url,+ f"{m3u8.total_segments:,}",+ item.real_url,m3u8.source,)- results = await _download_segments(m_segments, m3u8.total_segments, download, sem)- await _decrypt_segments((r.item for r in results), sem)- await _merge_segments(tuple(result.item.path for result in results), output)++ m_segments = await _download_segments(+ _create_media_segments(m3u8, temp_dir, item),+ m3u8.total_segments,+ download_fn,+ sem,+ )+ await _decrypt_segments(m_segments, sem)+ await _merge_segments(m_segments, output)return output@@ -166,7 +148,7 @@ async def _decrypt_segments(items: Iterable[MediaItem], sem: asyncio.BoundedSemaasync def decrypt(item: MediaItem) -> None:if key := HLSKey.get(item.extra_info):- logger.debug(f"Decrypting '{item.path}' with {key}")+ logger.debug("Decrypting '%s' with %s", item.path, key)content = await decrypter(await aio.read_bytes(item.path), key, item.headers)await aio.write_bytes(item.path, content)@@ -176,29 +158,33 @@ async def _decrypt_segments(items: Iterable[MediaItem], sem: asyncio.BoundedSemaasync def _download_segments(segments: Iterable[MediaItem],count: int,- download: Callable[[MediaItem], Awaitable[SegmentDownloadResult]],+ download_fn: Callable[[MediaItem], Awaitable[bool]],sem: asyncio.BoundedSemaphore,-) -> list[SegmentDownloadResult]:+) -> list[MediaItem]:++ async def download(seg_media_item: MediaItem) -> MediaItem | None:+ if await download_fn(seg_media_item):+ return seg_media_item+results = await aio.map(download,segments,task_limit=sem,)- n_successful = sum(1 for result in results if result.downloaded)- if n_successful != count:- msg = f"Download of some segments failed. Successful: {n_successful:,}/{count:,} "+ results = [item for item in results if item is not None]+ if len(results) != count:+ msg = f"Download of some segments failed. Successful: {len(results):,}/{count:,} "raise DownloadError("HLS Seg Error", msg)return results-async def _merge_segments(seg_paths: Sequence[Path], output: Path) -> None:- if len(seg_paths) == 1:- _ = await aio.move(seg_paths[0], output)- return-- await ffmpeg.raw_concat(seg_paths, output)+async def _merge_segments(results: Sequence[MediaItem], output: Path) -> None:+ if len(results) == 1:+ await aio.move(results[0].path, output)+ else:+ await ffmpeg.raw_concat((item.path for item in results), output)def _prepare_output_path(m3u8: M3U8, output: Path) -> Path:@@ -227,10 +213,12 @@ async def download(media_item: MediaItem, rendition: Rendition, download_fn: Dowtry:subs = await download(rendition.subtitle)except Exception:- logger.exception(f"Unable to download subtitles for {media_item.url}, Skipping")+ logger.exception("Unable to download subtitles for %s, Skipping", media_item.url)else:logger.warning(- f"Found subtitles for {media_item.url}, but CDL is currently unable to merge them. Subtitle were saved at '{subs}'"+ "Found subtitles for %s, but CDL is currently unable to merge them. Subtitles were saved at '%s'",+ media_item.url,+ subs,)return subsdiff --git a/cyberdrop_dl/downloader/http.py b/cyberdrop_dl/downloader/http.pyindex 26a39c2b4..d974fcaf6 100644--- a/cyberdrop_dl/downloader/http.py+++ b/cyberdrop_dl/downloader/http.py@@ -5,11 +5,12 @@ import contextlibimport dataclassesimport loggingimport os-from typing import TYPE_CHECKING, ClassVar+from pathlib import Path+from typing import TYPE_CHECKING, ClassVar, finalfrom aiohttp import ClientConnectorError, ClientError, ClientResponseError-from cyberdrop_dl import aio, constants, ffmpeg, storage+from cyberdrop_dl import aio, constants, env, ffmpeg, storagefrom cyberdrop_dl.clients.downloads import filter_by_duration, resolve_download_dirfrom cyberdrop_dl.downloader import hlsfrom cyberdrop_dl.exceptions import (@@ -21,8 +22,13 @@ from cyberdrop_dl.exceptions import (RestrictedFiletypeError,SkipDownloadError,)+from cyberdrop_dl.hasher import compute_in_place_hash+from cyberdrop_dl.progress.scraping import show_msg+from cyberdrop_dl.signature import simple_repr+from cyberdrop_dl.url_objects import MuxVideofrom cyberdrop_dl.utils import datesfrom cyberdrop_dl.utils.errors import error_handling_wrapper+from cyberdrop_dl.utils.m3u8 import Renditionif TYPE_CHECKING:import datetime@@ -31,8 +37,8 @@ if TYPE_CHECKING:from cyberdrop_dl.clients.downloads import DownloadClientfrom cyberdrop_dl.config import Configfrom cyberdrop_dl.manager import Manager+ from cyberdrop_dl.progress.scraping import ScrapingUIfrom cyberdrop_dl.url_objects import AbsoluteHttpURL, MediaItem- from cyberdrop_dl.utils.m3u8 import Renditionlogger = logging.getLogger(__name__)@@ -98,28 +104,33 @@ class Capacity:self._should_warn = True[email protected](slots=True)class Downloader:"""High level class that handles limiters, database checks, skip by config checks and retries"""SUPPORTS_RETRIES: ClassVar[bool] = True- manager: Manager = dataclasses.field(repr=False)log_prefix: str = "Download"- use_server_lock: bool = False-- _slots: int | None = None- _processed_items: set[str] = dataclasses.field(init=False, default_factory=set)- _current_attempt_filesize: dict[str, int] = dataclasses.field(init=False, default_factory=dict)- _semaphore: asyncio.Semaphore = dataclasses.field(init=False)- _server_locks: aio.WeakAsyncLocks[str] = dataclasses.field(- init=False, default_factory=aio.WeakAsyncLocks, repr=False- )- capacity: Capacity = dataclasses.field(default_factory=Capacity)- config: Config = dataclasses.field(init=False)-- def __post_init__(self) -> None:- self.config = self.manager.config- self.slots = self._slots++ @final+ def __init__(self, manager: Manager, slots: int | None = None, *, use_server_lock: bool = False) -> None:+ self.manager: Manager = manager+ self.use_server_lock: bool = use_server_lock+ self.capacity: Capacity = Capacity()+ self.config: Config = self.manager.config+ self._processed_items: set[str] = set()+ self._current_attempt_filesize: dict[str, int] = {}+ self._server_locks: aio.WeakAsyncLocks[str] = aio.WeakAsyncLocks()+ self._slots: int | None = slots+ self._semaphore: asyncio.Semaphore+ self._set_capacity_limit(slots)+ self.__post_init__()++ def __post_init__(self) -> None: ...++ __repr__ = simple_repr("slots", "use_server_lock", "log_prefix", "capacity", "_semaphore")++ @property+ def tui(self) -> ScrapingUI:+ return self.manager.scrape_mapper.tui@propertydef slots(self) -> int | None:@@ -127,16 +138,15 @@ class Downloader:@slots.setterdef slots(self, new_limit: int | None) -> None:- try:- sem = self._semaphore- except AttributeError:- pass- else:- if not (sem._waiters is None and sem._value == self._slots):- raise RuntimeError("Can't change download limits. Downloader is already in use")+ if not (self._semaphore._waiters is None and self._semaphore._value == self._slots):+ raise RuntimeError("Can't change download slots. Downloader is already in use")+ self._set_capacity_limit(new_limit)+ def _set_capacity_limit(self, slots: int | None) -> None:+ if slots is not None and slots < 1:+ raise ValueError("slots has to be >=1 or None (unlimited)")upper_limit = self.config.downloads.concurrency_per_domain- self._slots = min(new_limit or upper_limit, upper_limit)+ self._slots = min(slots or upper_limit, upper_limit)self._semaphore = asyncio.Semaphore(self._slots)self.capacity.limit = min(self._slots * 10, 50)@@ -155,19 +165,13 @@ class Downloader:raiselogger.error(f"{self.log_prefix} failed: {media_item.url} with error: {e!s}")-logger.info(- f"Retrying {self.log_prefix.lower()}: {media_item.url}, retry attempt: {media_item.attempts + 1}"+ "Retrying %s: %s, attempt: %s",+ self.log_prefix.lower(),+ media_item.url,+ media_item.attempts + 1,)- async def __finalize_download(self, media_item: MediaItem) -> None:- await aio.chmod(media_item.path, 0o666)- if media_item.is_segment:- return- await _set_mtime(media_item, self.config)- self.manager.scrape_mapper.tui.files.stats.completed += 1- logger.info(f"Download finished: {media_item.url}")-async def _check_skip_by_config(self, media_item: MediaItem) -> None:if not _is_allowed_filetype(media_item, self.config):raise RestrictedFiletypeError(origin=media_item)@@ -213,7 +217,7 @@ class Downloader:except SkipDownloadError as e:if not media_item.is_segment:logger.info(f"Download skipped {media_item.url}: {e}")- self.manager.scrape_mapper.tui.files.stats.skipped += 1+ self.tui.files.stats.skipped += 1except (DownloadError, ClientResponseError, InvalidContentTypeError):raise@@ -238,7 +242,7 @@ class Downloader:else:if downloaded:- await self.__finalize_download(media_item)+ await aio.chmod(media_item.path, 0o666)return downloaded@contextlib.asynccontextmanager@@ -251,77 +255,134 @@ class Downloader:):yield- async def run(self, media_item: MediaItem) -> bool:- if media_item.db_path in self._processed_items and not self.config.ignore_history:- return False-- async with self.__download_context(media_item):- downloaded = await self._download(media_item)-- if not downloaded:- return False- assert not media_item.is_segment- if await self.__skip_by_duration(media_item):- return False- await self.client.process_completed(media_item, media_item.domain)- await self.client.handle_media_item_completion(media_item, downloaded=True)- return True-async def __skip_by_duration(self, media_item: MediaItem) -> bool:proceed = not await filter_by_duration(media_item, self.config)await self.manager.database.history.add_duration(media_item.domain, media_item)if not proceed:logger.info(f"Download skipped {media_item.url} due to runtime restrictions")- await aio.unlink(media_item.path)+ await aio.unlink(media_item.path, missing_ok=True)await self.client.mark_incomplete(media_item, media_item.domain)- self.manager.scrape_mapper.tui.files.stats.skipped += 1+ self.tui.files.stats.skipped += 1return not proceed+ async def _prepare_multi_stream_output(self, media_item: MediaItem) -> None:+ media_item.download_folder = resolve_download_dir(media_item.download_folder, self.config)+ media_item.path = media_item.download_folder / media_item.filename+ media_item.download_filename = media_item.path.name+ await self.manager.database.history.add_download_filename(media_item.domain, media_item)+@error_handling_wrapper- async def download_hls(self, media_item: MediaItem, m3u8_group: Rendition) -> None:+ async def run(self, media_item: MediaItem, streams: Rendition | MuxVideo | None = None) -> None:if media_item.db_path in self._processed_items and not self.config.ignore_history:return- assert ffmpeg.is_installed()+ if streams is not None:+ assert ffmpeg.is_installed()+async with self.__download_context(media_item):- await self.__hls_download(media_item, m3u8_group)+ match streams:+ case None:+ await self._file(media_item)+ case Rendition():+ await self._hls(media_item, streams)+ case MuxVideo():+ await self._mux(media_item, streams)+ case _: # pyright: ignore[reportUnnecessaryComparison]+ raise ValueError(f"Unsupported streams: {streams!r}")++ if media_item.downloaded:+ await self._compute_hashes(media_item)++ async def _file(self, media_item: MediaItem) -> None:+ if not await self._download(media_item):+ return- async def __hls_download(self, media_item: MediaItem, rendition: Rendition) -> None:- media_item.download_folder = resolve_download_dir(media_item.download_folder, self.config)- media_item.path = media_item.download_folder / media_item.filename- media_item.download_filename = media_item.path.name- await self.manager.database.history.add_download_filename(media_item.domain, media_item)+ await self.__finish_download(media_item)++ async def _mux(self, media_item: MediaItem, mux: MuxVideo) -> None:+ await self._prepare_multi_stream_output(media_item)+ p_name = Path(media_item.filename)++ def create_stream_item(name: str, url: AbsoluteHttpURL) -> MediaItem:+ filename = p_name.with_suffix(f".{name}{constants.TempExt.PART}").name+ seg_item = media_item.as_segment(filename, url)+ seg_item.extra_info["MUX_STREAM"] = True+ return seg_item- with self.manager.scrape_mapper.tui.downloads.download_hls(+ logger.info(f"{self.log_prefix} starting (multistream video): {media_item.url}\n %s", mux.__json__())+ audio, video = create_stream_item("audio", mux.audio), create_stream_item("video", mux.video)+ results = await aio.map(self._download, (audio, video), task_limit=None)+ if not all(results):+ msg = f"Download of some streams failed. {dict(zip(('audio', 'video'), results, strict=True))}"+ raise DownloadError("Mux Download Error", msg)++ streams = hls.Streams(video.path, audio.path, None)+ await _merge_streams(media_item, streams)+ await self.__finish_download(media_item)++ async def _hls(self, media_item: MediaItem, rendition: Rendition) -> None:+ await self._prepare_multi_stream_output(media_item)+ with self.tui.downloads.download_hls(media_item.filename,media_item.domain,segments=sum(m.total_segments for m in rendition if m is not None),url=media_item.url,):- await self._hls_download(media_item, rendition)+ streams = await hls.download(media_item, rendition, self._download, self.client.http_client)+ await _merge_streams(media_item, streams)+ await _fixup_video(media_item)+ await self.__finish_download(media_item)- async def _hls_download(self, media_item: MediaItem, rendition: Rendition) -> None:- streams = await hls.download(media_item, rendition, self._download, self.client.http_client)- if not streams.audio:- await aio.move(streams.video, media_item.path)+ async def __finish_download(self, media_item: MediaItem) -> None:+ assert not media_item.is_segment+ media_item.downloaded = True+ if await self.__skip_by_duration(media_item):+ media_item.downloaded = False+ return- else:- # TODO: add remux method to ffmpeg to create an mkv file instead of mp4- # Subtitles format may be incompatible with mp4 and they will be silently dropped by ffmpeg- # so we leave them as independent files for now- logger.debug(f"Merging audio and video stream from {media_item.real_url}")- ffmpeg_result = await ffmpeg.merge((streams.video, streams.audio), media_item.path)+ await _set_mtime(media_item, self.config)+ self.tui.files.stats.completed += 1+ logger.info(f"Download finished: {media_item.url}")+ await self.client.mark_completed(media_item, media_item.domain)++ async def _compute_hashes(self, media_item: MediaItem) -> None:+ # TODO: move this to the scrape_mapper as a post-download task+ if self.config.hashing.mode is not constants.HashMode.IN_PLACE:+ return+ try:+ await compute_in_place_hash(self.manager.hasher, media_item)+ except Exception:+ logger.exception("Unable to compute hashes of '%s'", media_item.path)+ finally:+ self.manager.add_completed(media_item)+++async def _merge_streams(media_item: MediaItem, streams: hls.Streams) -> None:+ if not streams.audio:+ await aio.move(streams.video, media_item.path)+ return- if not ffmpeg_result.success:- raise DownloadError("FFmpeg Concat Error", ffmpeg_result.stderr, media_item)+ # TODO: add remux method to create an mkv file instead of mp4+ # Subtitles format may be incompatible with mp4 and they will be silently dropped by ffmpeg+ # so we leave them as independent files for now+ with show_msg(f"Merging {media_item.path.name}"):+ logger.debug("Merging audio and video stream for '%s' (%s)", media_item.path.name, media_item.real_url)+ result = await ffmpeg.merge(streams.video, streams.audio, media_item.path)- logger.debug(f"Running MP4 fixup ({media_item.real_url})")- ffmpeg_result = await ffmpeg.fixup_video(media_item.path)- if not ffmpeg_result.success:- raise DownloadError("FFmpeg Fixup Error", ffmpeg_result.stderr, media_item)- await self.client.process_completed(media_item, media_item.domain)- await self.client.handle_media_item_completion(media_item, downloaded=True)- await self.__finalize_download(media_item)+ if not result.success:+ raise DownloadError("FFmpeg Concat Error", result.stderr, media_item)+++async def _fixup_video(media_item: MediaItem) -> None:+ if not env.FFMPEG_FIX_HLS:+ return++ with show_msg(f"Optimizing {media_item.path.name}"):+ logger.debug("Fixing MP4 container with ffmpeg: '%s' (%s)", media_item.path, media_item.real_url)+ result = await ffmpeg.optimize(media_item.path)++ if not result.success:+ raise DownloadError("FFmpeg Fixup Error", result.stderr, media_item)def _is_allowed_filetype(media_item: MediaItem, config: Config) -> bool:@@ -356,9 +417,6 @@ def _filter_by_date(item_datetime: datetime.datetime, config: Config) -> bool:async def _set_mtime(media_item: MediaItem, config: Config) -> None:- if media_item.is_segment:- return-if not config.mtime:returndiff --git a/cyberdrop_dl/downloader/mega_nz.py b/cyberdrop_dl/downloader/mega_nz.pyindex d6a68cbd8..5560dc09e 100644--- a/cyberdrop_dl/downloader/mega_nz.py+++ b/cyberdrop_dl/downloader/mega_nz.py@@ -1,6 +1,5 @@from __future__ import annotations-import dataclassesfrom typing import TYPE_CHECKING, Any, ClassVar, final, overridefrom mega.chunker import MegaChunker, get_chunks@@ -11,16 +10,13 @@ from cyberdrop_dl.downloader.http import Downloaderif TYPE_CHECKING:from cyberdrop_dl.clients.response import AbstractResponse- from cyberdrop_dl.manager import Managerfrom cyberdrop_dl.progress import ProgressHookfrom cyberdrop_dl.url_objects import MediaItem@finalclass MegaDownloadClient(DownloadClient): # pyright: ignore[reportGeneralTypeIssues]- def __init__(self, manager: Manager) -> None:- super().__init__(manager)- self._supports_ranges = False+ SUPPORTS_RANGES: ClassVar[bool] = False@overrideasync def _append_content(self, media_item: MediaItem, hook: ProgressHook, resp: AbstractResponse[Any]) -> None:@@ -57,14 +53,10 @@ class MegaDownloadClient(DownloadClient): # pyright: ignore[reportGeneralTypeIsmedia_item.partial_file.touch()[email protected](slots=True)class MegaDownloader(Downloader):- _client: MegaDownloadClient = dataclasses.field(init=False)- SUPPORTS_RETRIES: ClassVar[bool] = True-def __post_init__(self) -> None:- super(MegaDownloader, self).__post_init__()- self._client = MegaDownloadClient(self.manager)+ super().__post_init__()+ self._client: MegaDownloadClient = MegaDownloadClient(self.manager) # pyright: ignore[reportUninitializedInstanceVariable]@property@overridediff --git a/cyberdrop_dl/env.py b/cyberdrop_dl/env.pyindex 719aeb10a..07f038c51 100644--- a/cyberdrop_dl/env.py+++ b/cyberdrop_dl/env.py@@ -17,14 +17,24 @@ def _env(name: str, *, censor: bool = False) -> str | None:return value-RUNNING_IN_TERMUX = bool(os.getenv("TERMUX_VERSION") or "com.termux" in os.getenv("PREFIX", sys.prefix))-FORCE_PORTRAIT_MODE = bool(_env("PORTRAIT_MODE") or RUNNING_IN_TERMUX)+def _cast_bool(value: bool | str | None) -> bool: # noqa: FBT001+ if not value:+ return False++ if value is True:+ return value++ return value.casefold() not in {"no", "0", "false"}+++RUNNING_IN_TERMUX = _cast_bool(os.getenv("TERMUX_VERSION") or "com.termux" in os.getenv("PREFIX", sys.prefix))+FORCE_PORTRAIT_MODE = _cast_bool(_env("PORTRAIT_MODE") or RUNNING_IN_TERMUX)DEBUG_LOG_FOLDER = _env("DEBUG_LOG_FOLDER")MAX_LOG_MSG_LENGTH = int(_env("MAX_LOG_MSG_LENGTH") or 0) or 5_000-DEBUG_MODE = bool(+DEBUG_MODE = _cast_bool(_env("DEBUG_MODE")or DEBUG_LOG_FOLDERor os.getenv("PYCHARM_HOSTED")@@ -37,7 +47,9 @@ ENABLE_DEBUG_CRAWLERS = (APPDATA_FOLDER = _env("APPDATA_FOLDER")WRITE_JSON_UI = int(_env("WRITE_JSON_UI") or 0) or None+FFMPEG_FIX_HLS = _cast_bool(_env("FFMPEG_FIX_HLS"))EDITOR = os.getenv("EDITOR")+CI = _cast_bool(os.getenv("CI"))# CRAWLERSdiff --git a/cyberdrop_dl/hasher.py b/cyberdrop_dl/hasher.pyindex 57229c259..f3c292c80 100644--- a/cyberdrop_dl/hasher.py+++ b/cyberdrop_dl/hasher.py@@ -165,7 +165,7 @@ class Hasher:}hashes = {algo: result for algo, task in task_map.items() if (result := task.result()) is not None}- logger.debug("hashes of '%s'\n%s", file, hashes)+ logger.debug("Hashes of '%s'\n%s", file, hashes)return hashes.get(HashAlgo.XXH128)@@ -200,7 +200,7 @@ class Hasher:referer,)except Exception:- logger.exception("Error hashing '%s'", file)+ logger.exception("Error computing %s hash of '%s'", hash_type, file)else:return hash_valuediff --git a/cyberdrop_dl/url_objects.py b/cyberdrop_dl/url_objects.pyindex c48c1501a..6b55b74bd 100644--- a/cyberdrop_dl/url_objects.py+++ b/cyberdrop_dl/url_objects.py@@ -120,6 +120,15 @@ class ScrapeItemType(IntEnum):logger = logging.getLogger(__name__)[email protected](slots=True, frozen=True)+class MuxVideo:+ video: AbsoluteHttpURL+ audio: AbsoluteHttpURL++ def __json__(self) -> dict[str, Any]:+ return {"video": str(self.video), "audio": str(self.audio)}++@final@dataclasses.dataclass(slots=True, kw_only=True)class MediaItem:@@ -203,6 +212,24 @@ class MediaItem:me["xxhash"] = f"xxh128:{self.xxhash}"return me+ def as_segment(self, filename: str, url: AbsoluteHttpURL) -> MediaItem:+ me = MediaItem(+ url=url,+ domain=self.domain,+ download_folder=self.download_folder,+ filename=filename,+ db_path=self.db_path,+ referer=self.url,+ album_id=self.album_id,+ ext=self.ext,+ parents=self.parents,+ uploaded_at=self.uploaded_at,+ is_segment=True,+ )+ me.headers = self.headers.copy()+ me.extra_info = self.extra_info.copy()+ return me+@dataclasses.dataclass(slots=True, frozen=True)class RetryInfo:diff --git a/pyproject.toml b/pyproject.tomlindex 64d5bb020..feeedcf52 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -1,6 +1,6 @@[project]name = "cyberdrop-dl-patched"-version = "10.8.0dev2"+version = "10.8.0dev3"authors = [{name = "Jacob B", email = "[email protected]"}]classifiers = ["Development Status :: 5 - Production/Stable",diff --git a/tests/crawlers/test_pawchive.py b/tests/crawlers/test_pawchive.pyindex df4342795..2298c4107 100644--- a/tests/crawlers/test_pawchive.py+++ b/tests/crawlers/test_pawchive.py@@ -5,10 +5,12 @@ from typing import Anyimport aiohttpimport pytest+from cyberdrop_dl import envfrom cyberdrop_dl.crawlers.kemono.kemono import _extract_urls, _has_adsfrom cyberdrop_dl.crawlers.kemono.models import Embed, File, UserPostModel, _parse_tagspytestmark = pytest.mark.http+pytestmark = pytest.mark.skipif(env.CI, reason="Skip requests")def request_json(url: str) -> Any:@@ -58,7 +60,7 @@ def test_post_validation(post_resp: dict[str, Any]) -> None:)assert post.published == datetime.datetime(2025, 5, 21, 18, 11, 4, tzinfo=datetime.UTC)assert post.added- assert post.added.date() == datetime.date(2026, 6, 11)+ assert post.added.date() >= datetime.date(2026, 6, 11)assert post.editedassert post.edited > datetime.datetime(2026, 7, 8, 3, 11, 18, tzinfo=datetime.UTC)assert post.timestamp == 1747851064diff --git a/tests/test_hls.py b/tests/test_hls.pyindex 4278f2422..b9105c307 100644--- a/tests/test_hls.py+++ b/tests/test_hls.py@@ -39,7 +39,7 @@ media-segment-00003.tsdef test_parse_segments() -> None:segments = [Segment(uri="/m3u8/test", base_uri="https://example.com") for _ in range(8)]- result = list(hls._parse_segments(segments))+ result = list(hls._create_segments(segments, len(segments)))assert len(result) == 8first = result[0]assert type(first) is hls.HLSSegment@@ -66,9 +66,7 @@ def test_create_media_segments() -> None:name="00023.cdl_hls",url=AbsoluteHttpURL("https://example.com/m3u8/test/segments001.ts"),)- result = list(hls._create_media_segments(item, [segment], folder / "video_hls"))- assert len(result) == 1- seg_item = result[0]+ seg_item = hls._create_media_segment(item, segment, folder / "video_hls")assert seg_item.url == segment.urlassert seg_item.download_folder == folder / "video_hls"assert seg_item.filename == segment.name@@ -116,4 +114,5 @@ def test_init_segments_should_be_include() -> None:m3u8 = M3U8(content)assert len(m3u8.segment_map) == 1assert len(m3u8.segments) == 5- assert len(hls._segments(m3u8)) == 6+ hls._check_segments(m3u8)+ assert m3u8.total_segments == 6diff --git a/uv.lock b/uv.lockindex b2e1a02fa..4b8b0f101 100644--- a/uv.lock+++ b/uv.lock@@ -683,7 +683,7 @@ wheels = [[[package]]name = "cyberdrop-dl-patched"-version = "10.8.0.dev2"+version = "10.8.0.dev3"source = { editable = "." }dependencies = [{ name = "aiodns", marker = "sys_platform != 'android' and sys_platform != 'win32'" },