Skip to content

Bulk asynchronous downloader for multiple file hosts

Feature: Min/Max Audio & Video Duration Config Options (#546)

Jacobfcd082b93f4f
diff --git a/cyberdrop_dl/clients/download_client.py b/cyberdrop_dl/clients/download_client.py
index b1d1a9289..dcbc6f726 100644
--- a/cyberdrop_dl/clients/download_client.py
+++ b/cyberdrop_dl/clients/download_client.py
@@ -12,6 +12,7 @@ from typing import TYPE_CHECKING
import aiofiles
import aiohttp
from aiohttp import ClientSession
+from videoprops import get_audio_properties, get_video_properties
from yarl import URL
from cyberdrop_dl.clients.errors import (
@@ -58,6 +59,48 @@ def limiter(func: Callable) -> Any:
return wrapper
+def check_file_duration(media_item: MediaItem, file_duration_limits: dict) -> bool:
+ """Checks the file runtime against the config runtime limits."""
+
+ is_video = media_item.ext.lower() in FILE_FORMATS["Videos"]
+ is_audio = media_item.ext.lower() in FILE_FORMATS["Audio"]
+ 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 = file_duration_limits
+ min_video_duration: float = duration_limits.minimum_video_duration.total_seconds()
+ max_video_duration: float = duration_limits.maximum_video_duration.total_seconds()
+ min_audio_duration: float = duration_limits.minimum_audio_duration.total_seconds()
+ 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(media_item)
+ 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")
+ if is_video:
+ return min_video_duration <= media_item.duration <= max_video_duration
+ return min_audio_duration <= media_item.duration <= max_audio_duration
+
+
class DownloadClient:
"""AIOHTTP operations for downloading."""
@@ -233,7 +276,7 @@ class DownloadClient:
async def download_file(self, manager: Manager, domain: str, media_item: MediaItem) -> bool:
"""Starts a file."""
if self.manager.config_manager.settings_data.download_options.skip_download_mark_completed:
- log(f"Download Skip {media_item.url} due to mark completed option", 10)
+ log(f"Download Removed {media_item.url} due to mark completed option", 10)
self.manager.progress_manager.download_progress.add_skipped()
# set completed path
await self.process_completed(media_item, domain)
@@ -249,6 +292,14 @@ class DownloadClient:
downloaded = await self._download(domain, manager, media_item, save_content)
if downloaded:
media_item.partial_file.rename(media_item.complete_file)
+ proceed = check_file_duration(media_item, self.manager.config_manager.settings_data.media_duration_limits)
+ 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)
+ media_item.complete_file.unlink()
+ await self.mark_incomplete(media_item, domain)
+ self.manager.progress_manager.download_progress.add_skipped()
+ return False
await self.process_completed(media_item, domain)
await self.handle_media_item_completion(media_item, downloaded=True)
return downloaded
diff --git a/cyberdrop_dl/clients/errors.py b/cyberdrop_dl/clients/errors.py
index cceaff743..55daf898a 100644
--- a/cyberdrop_dl/clients/errors.py
+++ b/cyberdrop_dl/clients/errors.py
@@ -127,6 +127,13 @@ class RestrictedFiletypeError(CDLBaseError):
super().__init__(ui_message, origin=origin)
+class DurationError(CDLBaseError):
+ def __init__(self, origin: ScrapeItem | MediaItem | URL | None = None) -> None:
+ """THis error will be thrown when the file duration is not allowed by the config."""
+ ui_message = "Duration Not Allowed"
+ super().__init__(ui_message, origin=origin)
+
+
class MediaFireError(CDLBaseError):
def __init__(
self, status: str | int, message: str | None = None, origin: ScrapeItem | MediaItem | URL | None = None
diff --git a/cyberdrop_dl/config_definitions/config_settings.py b/cyberdrop_dl/config_definitions/config_settings.py
index 09d1abd30..101f130e2 100644
--- a/cyberdrop_dl/config_definitions/config_settings.py
+++ b/cyberdrop_dl/config_definitions/config_settings.py
@@ -103,6 +103,26 @@ class FileSizeLimits(BaseModel):
return value.human_readable(decimal=True)
+class MediaDurationLimits(BaseModel):
+ maximum_video_duration: timedelta = timedelta(seconds=0)
+ maximum_audio_duration: timedelta = timedelta(seconds=0)
+ minimum_video_duration: timedelta = timedelta(seconds=0)
+ minimum_audio_duration: timedelta = timedelta(seconds=0)
+
+ @field_validator("*", mode="before")
+ @staticmethod
+ def parse_runtime_duration(input_date: timedelta | str | int | None) -> timedelta:
+ """Parses `datetime.timedelta`, `str` or `int` into a timedelta format.
+ for `str`, the expected format is `value unit`, ex: `5 days`, `10 minutes`, `1 year`
+ valid units:
+ year(s), week(s), day(s), hour(s), minute(s), second(s), millisecond(s), microsecond(s)
+ for `int`, value is assumed as `days`
+ """
+ if input_date is None:
+ return timedelta(seconds=0)
+ return parse_duration_to_timedelta(input_date)
+
+
class IgnoreOptions(BaseModel):
exclude_videos: bool = False
exclude_images: bool = False
@@ -207,6 +227,9 @@ class ConfigSettings(AliasModel):
validation_alias="Dupe_Cleanup_Options", default=DupeCleanupOptions()
)
file_size_limits: FileSizeLimits = Field(validation_alias="File_Size_Limits", default=FileSizeLimits())
+ media_duration_limits: MediaDurationLimits = Field(
+ validation_alias="Media_Duration_Limits", default=MediaDurationLimits()
+ )
files: Files = Field(validation_alias="Files", default=Files())
ignore_options: IgnoreOptions = Field(validation_alias="Ignore_Options", default=IgnoreOptions())
logs: Logs = Field(validation_alias="Logs", default=Logs())
diff --git a/cyberdrop_dl/downloader/downloader.py b/cyberdrop_dl/downloader/downloader.py
index 62ca2cfa9..9b66eadd7 100644
--- a/cyberdrop_dl/downloader/downloader.py
+++ b/cyberdrop_dl/downloader/downloader.py
@@ -13,6 +13,7 @@ from filedate import File
from cyberdrop_dl.clients.errors import (
DownloadError,
+ DurationError,
InsufficientFreeSpaceError,
RestrictedFiletypeError,
create_error_msg,
@@ -115,6 +116,10 @@ class Downloader:
raise InsufficientFreeSpaceError(origin=media_item)
if not self.manager.download_manager.check_allowed_filetype(media_item):
raise RestrictedFiletypeError(origin=media_item)
+ if not self.manager.download_manager.pre_check_duration(
+ media_item, self.manager.config_manager.settings_data.media_duration_limits
+ ):
+ raise DurationError(origin=media_item)
def set_file_datetime(self, media_item: MediaItem, complete_file: Path) -> None:
"""Sets the file's datetime."""
@@ -155,6 +160,7 @@ class Downloader:
origin = media_item.referer
try:
media_item.current_attempt = media_item.current_attempt or 1
+ media_item.duration = await self.manager.db_manager.history_table.get_duration(self.domain, media_item)
self.check_file_can_download(media_item)
downloaded = await self.client.download_file(self.manager, self.domain, media_item)
if downloaded:
diff --git a/cyberdrop_dl/managers/download_manager.py b/cyberdrop_dl/managers/download_manager.py
index 0c2957bde..d1ef5e241 100644
--- a/cyberdrop_dl/managers/download_manager.py
+++ b/cyberdrop_dl/managers/download_manager.py
@@ -6,6 +6,7 @@ from contextlib import asynccontextmanager
from shutil import disk_usage
from typing import TYPE_CHECKING
+from cyberdrop_dl.clients.download_client import check_file_duration
from cyberdrop_dl.utils.constants import FILE_FORMATS
from cyberdrop_dl.utils.logger import log_debug
@@ -95,3 +96,10 @@ class DownloadManager:
if media_item.ext.lower() in FILE_FORMATS["Audio"] and ignore_options.exclude_audio:
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 check_file_duration(media_item, self.manager.config_manager.settings_data.media_duration_limits)
diff --git a/cyberdrop_dl/utils/data_enums_classes/url_objects.py b/cyberdrop_dl/utils/data_enums_classes/url_objects.py
index 3531a40da..28dbd359e 100644
--- a/cyberdrop_dl/utils/data_enums_classes/url_objects.py
+++ b/cyberdrop_dl/utils/data_enums_classes/url_objects.py
@@ -37,6 +37,7 @@ class MediaItem:
filename: str
original_filename: str | None = None
debrid_link: URL | None = field(default=None, hash=False, compare=False)
+ duration: float | None = field(default=None, hash=False, compare=False)
ext: str = ""
# exclude from __init__
diff --git a/cyberdrop_dl/utils/database/table_definitions.py b/cyberdrop_dl/utils/database/table_definitions.py
index bc5b02cc1..68500d8d9 100644
--- a/cyberdrop_dl/utils/database/table_definitions.py
+++ b/cyberdrop_dl/utils/database/table_definitions.py
@@ -21,6 +21,7 @@ create_fixed_history = """CREATE TABLE IF NOT EXISTS media_copy (
download_filename TEXT,
original_filename TEXT,
file_size INT,
+ duration FLOAT,
completed INTEGER NOT NULL,
PRIMARY KEY (domain, url_path, original_filename)
);"""
diff --git a/cyberdrop_dl/utils/database/tables/history_table.py b/cyberdrop_dl/utils/database/tables/history_table.py
index c358ef3d3..53e4940d3 100644
--- a/cyberdrop_dl/utils/database/tables/history_table.py
+++ b/cyberdrop_dl/utils/database/tables/history_table.py
@@ -184,6 +184,29 @@ class HistoryTable:
)
await self.db_conn.commit()
+ async def add_duration(self, domain: str, media_item: MediaItem) -> None:
+ """Add the file size to the db."""
+
+ url_path = get_db_path(media_item.url, str(media_item.referer))
+ duration = media_item.duration
+ await self.db_conn.execute(
+ """UPDATE media SET duration=? WHERE domain = ? and url_path = ?""",
+ (duration, domain, url_path),
+ )
+ await self.db_conn.commit()
+
+ async def get_duration(self, domain: str, media_item: MediaItem) -> float:
+ """Returns the duration from the database."""
+
+ url_path = get_db_path(media_item.url, str(media_item.referer))
+ cursor = await self.db_conn.cursor()
+ result = await cursor.execute(
+ """SELECT duration FROM media WHERE domain = ? and url_path = ?""",
+ (domain, url_path),
+ )
+ sql_duration = await result.fetchone()
+ return sql_duration[0] if sql_duration else None
+
async def add_download_filename(self, domain: str, media_item: MediaItem) -> None:
"""Add the download_filename to the db."""
url_path = get_db_path(media_item.url, str(media_item.referer))
@@ -334,3 +357,7 @@ class HistoryTable:
if "file_size" not in current_cols:
await self.db_conn.execute("""ALTER TABLE media ADD COLUMN file_size INT""")
await self.db_conn.commit()
+
+ if "duration" not in current_cols:
+ await self.db_conn.execute("""ALTER TABLE media ADD COLUMN duration FLOAT""")
+ await self.db_conn.commit()
diff --git a/docs/SUMMARY.md b/docs/SUMMARY.md
index 982aac25f..26080da0a 100644
--- a/docs/SUMMARY.md
+++ b/docs/SUMMARY.md
@@ -26,6 +26,7 @@
* [Files](reference/configuration-options/settings/files.md)
* [Ignore Options](reference/configuration-options/settings/ignore_options.md)
* [Logs](reference/configuration-options/settings/logs.md)
+ * [Media Duration Limits](reference/configuration-options/settings/media_duration_limits.md)
* [Runtime Options](reference/configuration-options/settings/runtime_options.md)
* [Sorting](reference/configuration-options/settings/sorting.md)
* [Global Settings](reference/configuration-options/global-settings/README.md)
diff --git a/docs/reference/cli-arguments.md b/docs/reference/cli-arguments.md
index cd214a74b..c5295a4e4 100644
--- a/docs/reference/cli-arguments.md
+++ b/docs/reference/cli-arguments.md
@@ -203,6 +203,12 @@ file_size_limits:
--minimum-other-size MINIMUM_OTHER_SIZE
--minimum-video-size MINIMUM_VIDEO_SIZE
+media_duration_limits:
+ --maximum-video-duration MAXIMUM_VIDEO_DURATION
+ --maximum-audio-duration MAXIMUM_AUDIO_DURATION
+ --minimum-video-duration MINIMUM_VIDEO_DURATION
+ --minimum-audio-duration MINIMUM_AUDIO_DURATION
+
files:
-i INPUT_FILE, --input-file INPUT_FILE
-d DOWNLOAD_FOLDER, --download-folder DOWNLOAD_FOLDER
diff --git a/docs/reference/configuration-options/settings/logs.md b/docs/reference/configuration-options/settings/logs.md
index 67c4a594d..bef15f9e6 100644
--- a/docs/reference/configuration-options/settings/logs.md
+++ b/docs/reference/configuration-options/settings/logs.md
@@ -92,7 +92,7 @@ With `rotate_logs` enabled, this setting specifies the retention period for log
- A `timedelta` input is expected to be a valid ISO 8601 timespan, ex: `P10DT2H30M10S`
- An `int` input is assumed to be the number of days
-- A `str` input is expected to be in the format; `<value> <unit>`, ex: `10 days`.
+- A `str` input is expected to be in the format; `<value> <unit>`, ex: `10 days`.
- A `null` value will disable automatic delection of logs
diff --git a/docs/reference/configuration-options/settings/media_duration_limits.md b/docs/reference/configuration-options/settings/media_duration_limits.md
new file mode 100644
index 000000000..a00258b6e
--- /dev/null
+++ b/docs/reference/configuration-options/settings/media_duration_limits.md
@@ -0,0 +1,18 @@
+# Duration Limits
+
+You can provide the maximum and minimum duration for audio and video files.
+
+| Type | Default |
+|-------------------|----------|
+| `timedelta` | `0s`|
+
+- A `timedelta` input is expected to be a valid ISO 8601 timespan, ex: `P10DT2H30M10S`
+- An `int` input is assumed to be the number of days
+- A `str` input is expected to be in the format; `<value> <unit>`, ex: `10 days`.
+
+Setting any of these options to `0` means that limit is `disabled`
+
+- `minimum_audio_duration`
+- `maximum_audio_duration`
+- `minimum_video_duration`
+- `maximum_video_duration`