Skip to content

Bulk asynchronous downloader for multiple file hosts

feat: check media duration before download (#1464)

Jacobae12cf89a150
diff --git a/cyberdrop_dl/clients/download_client.py b/cyberdrop_dl/clients/download_client.py
index 3727e9dd6..42cba5985 100644
--- a/cyberdrop_dl/clients/download_client.py
+++ b/cyberdrop_dl/clients/download_client.py
@@ -270,7 +270,7 @@ class DownloadClient:
if downloaded:
await asyncio.to_thread(media_item.partial_file.rename, media_item.complete_file)
if not media_item.is_segment:
- proceed = self.client_manager.check_file_duration(media_item)
+ proceed = await self.client_manager.check_file_duration(media_item)
await self.manager.db_manager.history_table.add_duration(domain, media_item)
if not proceed:
log(f"Download Skip {media_item.url} due to runtime restrictions", 10)
diff --git a/cyberdrop_dl/downloader/downloader.py b/cyberdrop_dl/downloader/downloader.py
index 13541d4a4..93ac749d3 100644
--- a/cyberdrop_dl/downloader/downloader.py
+++ b/cyberdrop_dl/downloader/downloader.py
@@ -312,7 +312,7 @@ class Downloader:
await self.manager.storage_manager.check_free_space(media_item)
if not self.manager.client_manager.check_allowed_filetype(media_item):
raise RestrictedFiletypeError(origin=media_item)
- if not self.manager.client_manager.pre_check_duration(media_item):
+ if not await self.manager.client_manager.check_file_duration(media_item):
raise DurationError(origin=media_item)
if not self.manager.client_manager.check_allowed_date_range(media_item):
raise RestrictedDateRangeError(origin=media_item)
diff --git a/cyberdrop_dl/exceptions.py b/cyberdrop_dl/exceptions.py
index 0e6cf4650..f1b254377 100644
--- a/cyberdrop_dl/exceptions.py
+++ b/cyberdrop_dl/exceptions.py
@@ -158,10 +158,11 @@ class RestrictedFiletypeError(CDLBaseError):
class DurationError(CDLBaseError):
- def __init__(self, origin: ScrapeItem | MediaItem | URL | None = None) -> None:
+ def __init__(self, origin: MediaItem) -> None:
"""THis error will be thrown when the file duration is not allowed by the config."""
ui_failure = "Duration Not Allowed"
- super().__init__(ui_failure, origin=origin)
+ message = f"Duration ({origin.duration}s) out of config range"
+ super().__init__(ui_failure, message=message, origin=origin)
class ScrapeError(CDLBaseError):
diff --git a/cyberdrop_dl/managers/client_manager.py b/cyberdrop_dl/managers/client_manager.py
index a3935c172..c6a9e4759 100644
--- a/cyberdrop_dl/managers/client_manager.py
+++ b/cyberdrop_dl/managers/client_manager.py
@@ -17,7 +17,6 @@ from aiohttp_client_cache.response import CachedResponse
from aiohttp_client_cache.session import CachedSession
from aiolimiter import AsyncLimiter
from bs4 import BeautifulSoup
-from videoprops import get_audio_properties, get_video_properties
from cyberdrop_dl import constants, env
from cyberdrop_dl.clients.download_client import DownloadClient
@@ -34,6 +33,7 @@ from cyberdrop_dl.exceptions import (
from cyberdrop_dl.ui.prompts.user_prompts import get_cookies_from_browsers
from cyberdrop_dl.utils.aio import WeakAsyncLocks
from cyberdrop_dl.utils.cookie_management import read_netscape_files
+from cyberdrop_dl.utils.ffmpeg import probe
from cyberdrop_dl.utils.logger import log, log_debug, log_spacer
_VALID_EXTENSIONS = (
@@ -224,13 +224,6 @@ class ClientManager:
return False
return not (ignore_options.exclude_other and media_item.ext.lower() not in _VALID_EXTENSIONS)
- def pre_check_duration(self, media_item: MediaItem) -> bool:
- """Checks if the download is above the maximum runtime."""
- if not media_item.duration:
- return True
-
- return self.check_file_duration(media_item)
-
def check_allowed_date_range(self, media_item: MediaItem) -> bool:
"""Checks if the file is published within the date range configured."""
if not media_item.datetime:
@@ -444,7 +437,7 @@ class ClientManager:
return bool(soup.select_one(CloudflareTurnstile.ALL_SELECTORS))
- def check_file_duration(self, media_item: MediaItem) -> bool:
+ async def check_file_duration(self, media_item: MediaItem) -> bool:
"""Checks the file runtime against the config runtime limits."""
if media_item.is_segment:
return True
@@ -454,16 +447,6 @@ class ClientManager:
if not (is_video or is_audio):
return True
- def get_duration() -> float | None:
- if media_item.duration:
- return media_item.duration
- props: dict = {}
- if is_video:
- props: dict = get_video_properties(str(media_item.complete_file))
- elif is_audio:
- props: dict = get_audio_properties(str(media_item.complete_file))
- return float(props.get("duration", 0)) or None
-
duration_limits = self.manager.config.media_duration_limits
min_video_duration: float = duration_limits.minimum_video_duration.total_seconds()
max_video_duration: float = duration_limits.maximum_video_duration.total_seconds()
@@ -471,21 +454,44 @@ class ClientManager:
max_audio_duration: float = duration_limits.maximum_audio_duration.total_seconds()
video_duration_limits = min_video_duration, max_video_duration
audio_duration_limits = min_audio_duration, max_audio_duration
+
if is_video and not any(video_duration_limits):
return True
if is_audio and not any(audio_duration_limits):
return True
- duration: float = get_duration() # type: ignore
+ async def get_duration() -> float | None:
+ if media_item.duration:
+ return media_item.duration
+
+ if media_item.downloaded:
+ properties = await probe(media_item.complete_file)
+
+ else:
+ headers = self.download_client._get_download_headers(media_item.domain, media_item.referer)
+ properties = await probe(media_item.url, headers=headers)
+
+ if is_video and (video := properties.video):
+ return video.duration
+ if is_audio and (audio := properties.audio):
+ return audio.duration
+ return None
+
+ duration: float | None = await get_duration()
media_item.duration = duration
+
if duration is None:
return True
- max_video_duration = max_video_duration or float("inf")
- max_audio_duration = max_audio_duration or float("inf")
+ await self.manager.db_manager.history_table.add_duration(media_item.domain, media_item)
+
if is_video:
- return min_video_duration <= media_item.duration <= max_video_duration
- return min_audio_duration <= media_item.duration <= max_audio_duration
+ max_video_duration = max_video_duration or float("inf")
+
+ return min_video_duration <= duration <= max_video_duration
+
+ max_audio_duration = max_audio_duration or float("inf")
+ return min_audio_duration <= duration <= max_audio_duration
async def close(self) -> None:
await self.flaresolverr.close()
diff --git a/cyberdrop_dl/utils/ffmpeg.py b/cyberdrop_dl/utils/ffmpeg.py
index 688f9918c..1cfef2de4 100644
--- a/cyberdrop_dl/utils/ffmpeg.py
+++ b/cyberdrop_dl/utils/ffmpeg.py
@@ -24,6 +24,8 @@ from cyberdrop_dl.utils.utilities import get_valid_dict, is_absolute_http_url
if TYPE_CHECKING:
from collections.abc import Generator, Mapping, Sequence
+ from cyberdrop_dl.data_structures import AbsoluteHttpURL
+
_CMD: TypeAlias = Sequence[str | Path]
@@ -58,7 +60,7 @@ def which_ffprobe() -> str | None:
global _FFPROBE_AVAILABLE
try:
bin_path = shutil.which("ffprobe") or _builtin_ffprobe()
- _FFPROBE_AVAILABLE = True
+ _FFPROBE_AVAILABLE = True # pyright: ignore[reportConstantRedefinition]
return bin_path
except RuntimeError:
return
@@ -101,10 +103,10 @@ async def probe(input: Path, /) -> FFprobeResult: ...
@overload
-async def probe(input: URL, /, *, headers: Mapping[str, str] | None = None) -> FFprobeResult: ...
+async def probe(input: AbsoluteHttpURL, /, *, headers: Mapping[str, str] | None = None) -> FFprobeResult: ...
-async def probe(input: Path | URL, /, *, headers: Mapping[str, str] | None = None) -> FFprobeResult:
+async def probe(input: Path | AbsoluteHttpURL, /, *, headers: Mapping[str, str] | None = None) -> FFprobeResult:
assert _FFPROBE_AVAILABLE
if isinstance(input, URL):
assert is_absolute_http_url(input)
@@ -187,9 +189,9 @@ class Duration(NamedTuple):
seconds: float = 0
@staticmethod
- def parse(duration: float | str) -> float:
+ def parse(duration: float | str) -> TruncatedFloat:
try:
- return float(duration)
+ return TruncatedFloat(duration)
except (ValueError, TypeError):
pass
@@ -205,7 +207,7 @@ class Duration(NamedTuple):
missing_parts = [0 for _ in range(3 - len(time_parts))]
seconds = float(Fraction(time_parts.pop(-1)))
int_parts = map(int, (days, *missing_parts, *time_parts))
- return Duration(*int_parts, seconds=seconds).as_timedelta().total_seconds()
+ return TruncatedFloat(Duration(*int_parts, seconds=seconds).as_timedelta().total_seconds())
def as_timedelta(self) -> timedelta:
return timedelta(**self._asdict())
@@ -223,7 +225,7 @@ class FFprobeOutput(TypedDict, total=False):
class Tags(CIMultiDictProxy[Any]): ...
-class FPS(float):
+class TruncatedFloat(float):
def __str__(self) -> str:
return str(int(self)) if self.is_integer() else f"{self:.2f}"
@@ -234,13 +236,9 @@ class Stream:
codec_name: str
codec_type: str
bitrate: int | None
- duration: float | None
+ duration: TruncatedFloat | None
tags: Tags
- @property
- def length(self) -> float | None:
- return self.duration
-
@property
def codec(self) -> str:
return self.codec_name
@@ -278,7 +276,7 @@ class AudioStream(Stream):
class VideoStream(Stream):
width: int | None
height: int | None
- fps: FPS | None
+ fps: TruncatedFloat | None
resolution: str | None
codec_type: Literal["video"] = "video"
@@ -291,7 +289,7 @@ class VideoStream(Stream):
resolution: str | None = f"{width}x{height}"
if (avg_fps := stream_info.get("avg_frame_rate")) and str(avg_fps) not in {"0/0", "0", "0.0"}:
- fps: FPS | None = FPS(Fraction(avg_fps))
+ fps: TruncatedFloat | None = TruncatedFloat(Fraction(avg_fps))
defaults = super(VideoStream, cls).validate(stream_info)
return defaults | {"width": width, "height": height, "fps": fps, "resolution": resolution}
diff --git a/cyberdrop_dl/utils/sorting.py b/cyberdrop_dl/utils/sorting.py
index e2dd1f4e2..0b88c6e06 100644
--- a/cyberdrop_dl/utils/sorting.py
+++ b/cyberdrop_dl/utils/sorting.py
@@ -3,17 +3,16 @@ from __future__ import annotations
import asyncio
import itertools
from datetime import datetime
-from fractions import Fraction
from pathlib import Path
from subprocess import CalledProcessError
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, Any
import imagesize
-from videoprops import get_audio_properties, get_video_properties
from cyberdrop_dl import constants
from cyberdrop_dl.constants import FILE_FORMATS
from cyberdrop_dl.utils import strings
+from cyberdrop_dl.utils.ffmpeg import probe
from cyberdrop_dl.utils.logger import log, log_with_color
from cyberdrop_dl.utils.utilities import purge_dir_tree
@@ -134,13 +133,16 @@ class Sorter:
"""Sorts an audio file into the sorted audio folder."""
if not self.audio_format:
return
+
bitrate = duration = sample_rate = None
try:
- props: dict = get_audio_properties(str(file))
- duration = int(float(props.get("duration", 0))) or None
- bitrate = int(float(props.get("bit_rate", 0))) or None
- sample_rate = int(float(props.get("sample_rate", 0))) or None
- except (RuntimeError, CalledProcessError):
+ properties = await probe(file)
+ if audio := properties.audio:
+ duration = audio.duration
+ bitrate = audio.bitrate
+ sample_rate = audio.sample_rate
+
+ except (RuntimeError, CalledProcessError, OSError):
log(f"Unable to get audio properties of '{file}'")
if await self._process_file_move(
@@ -166,6 +168,7 @@ class Sorter:
else:
# imagesize returns (-1, -1) for unsupported/corrupted images
width = height = resolution = None
+
except (OSError, ValueError):
log(f"Unable to get some image properties of '{file}'")
@@ -184,35 +187,28 @@ class Sorter:
if not self.video_format:
return
- codec = duration = fps = height = resolution = width = None
+ codec = duration = framerate = height = resolution = width = None
try:
- props: dict = get_video_properties(str(file))
- width = int(float(props.get("width", 0))) or None
- height = int(float(props.get("height", 0))) or None
- if width and height:
- resolution = f"{width}x{height}"
-
- codec: str | None = props.get("codec_name")
- duration = int(float(props.get("duration", 0))) or None
- fps = (
- float(Fraction(props.get("avg_frame_rate", 0)))
- if str(props.get("avg_frame_rate", 0)) not in {"0/0", "0"}
- else None
- )
- except (RuntimeError, CalledProcessError):
+ properties = await probe(file)
+ if video := properties.video:
+ width = video.width
+ height = video.height
+ resolution = video.resolution
+ codec = video.codec_name
+ duration = video.duration
+ framerate = video.fps
+
+ except (RuntimeError, CalledProcessError, OSError):
log(f"Unable to get some video properties of '{file}'")
- if fps is not None:
- fps = str(int(fps)) if fps.is_integer() else f"{fps:.2f}"
-
if await self._process_file_move(
file,
base_name,
self.video_format,
codec=codec,
duration=duration,
- fps=fps,
+ fps=framerate,
height=height,
resolution=resolution,
width=width,
@@ -223,10 +219,11 @@ class Sorter:
"""Sorts an other file into the sorted other folder."""
if not self.other_format:
return
+
if await self._process_file_move(file, base_name, self.other_format):
self.manager.progress_manager.sort_progress.increment_other()
- async def _process_file_move(self, file: Path, base_name: str, format_str: str, **kwargs) -> bool:
+ async def _process_file_move(self, file: Path, base_name: str, format_str: str, **kwargs: Any) -> bool:
file_date = await get_modified_date(file)
file_date_us = file_date.strftime("%Y-%d-%m")
file_date_iso = file_date.strftime("%Y-%m-%d")
diff --git a/tests/test_ffmpeg.py b/tests/test_ffmpeg.py
new file mode 100644
index 000000000..e32ae4da5
--- /dev/null
+++ b/tests/test_ffmpeg.py
@@ -0,0 +1,29 @@
+import pytest
+
+from cyberdrop_dl.data_structures import AbsoluteHttpURL
+from cyberdrop_dl.utils import ffmpeg
+
+FFPROBE_IS_INSTALLED = bool(ffmpeg.get_ffprobe_version())
+
+pytestmark = pytest.mark.skipif(not FFPROBE_IS_INSTALLED, reason="ffprobe is not installed")
+
+
+async def test_ffprobe_video_url() -> None:
+ output = await ffmpeg.probe(AbsoluteHttpURL("https://data.saint2.cr/data/LM54NzGj8PO.mp4"))
+ assert output.audio
+ assert output.audio.codec == "aac"
+ assert output.audio.duration == 7.808
+ assert str(output.audio.duration) == "7.81"
+ assert output.audio.sample_rate == 48000
+
+ assert output.video
+ assert output.video.codec == "h264"
+ assert output.video.bitrate and output.video.bitrate > 785000
+ assert output.video.fps == 30.0
+ assert output.video.width == 480
+ assert output.video.height == 854
+
+ tags = output.video.tags
+ assert tags["language"] == "und"
+ assert tags["handler_name"] == "VideoHandler"
+ assert tags["encoder"] == "AVC Coding"