Bulk asynchronous downloader for multiple file hosts
Python asynciobunkrcyberdropdownloaderdropboxfilestergofilegoogle-drivemediafiremegamega-nzonedrivepatreonpawchivepinterestpixeldraintransfer-ittwitchtwittervk
feat: add dates for log management (#444)
datawhoresce666edc8dc8
diff --git a/cyberdrop_dl/config_definitions/authentication_settings.py b/cyberdrop_dl/config_definitions/authentication_settings.pyindex 350e7f7c7..3c7c53653 100644--- a/cyberdrop_dl/config_definitions/authentication_settings.py+++ b/cyberdrop_dl/config_definitions/authentication_settings.py@@ -1,6 +1,6 @@from pydantic import BaseModel, Field-from .custom_types import AliasModel+from .pydantic.custom_types import AliasModelclass ForumAuth(BaseModel):diff --git a/cyberdrop_dl/config_definitions/config_settings.py b/cyberdrop_dl/config_definitions/config_settings.pyindex 7243efe1e..f92931adf 100644--- a/cyberdrop_dl/config_definitions/config_settings.py+++ b/cyberdrop_dl/config_definitions/config_settings.py@@ -1,14 +1,16 @@+from datetime import timedeltafrom logging import DEBUGfrom pathlib import Pathfrom typing import Literalfrom pydantic import BaseModel, ByteSize, Field, NonNegativeInt, PositiveInt, field_serializer, field_validator+from cyberdrop_dl.config_definitions.pydantic.validators import parse_duration_to_timedeltafrom cyberdrop_dl.utils.constants import APP_STORAGE, BROWSERS, DOWNLOAD_STORAGEfrom cyberdrop_dl.utils.data_enums_classes.hash import Hashingfrom cyberdrop_dl.utils.data_enums_classes.supported_domains import SUPPORTED_SITES_DOMAINS-from .custom_types import AliasModel, HttpAppriseURL, NonEmptyStr+from .pydantic.custom_types import AliasModel, HttpAppriseURL, NonEmptyStrclass DownloadOptions(BaseModel):@@ -49,6 +51,7 @@ class Logs(AliasModel):scrape_error_urls: Path = Field(Path("Scrape_Error_URLs.csv"), validation_alias="scrape_error_urls_filename")rotate_logs: bool = Falselog_line_width: PositiveInt = Field(default=240, ge=50)+ logs_expire_after: timedelta | None = None@field_validator("webhook", mode="before")@classmethod@@ -67,6 +70,22 @@ class Logs(AliasModel):def fix_other_logs_extensions(cls, value: Path) -> Path:return value.with_suffix(".csv")+ @field_validator("logs_expire_after", mode="before")+ @staticmethod+ def parse_logs_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 None+ return parse_duration_to_timedelta(input_date)+class FileSizeLimits(BaseModel):maximum_image_size: ByteSize = ByteSize(0)diff --git a/cyberdrop_dl/config_definitions/global_settings.py b/cyberdrop_dl/config_definitions/global_settings.pyindex 1ab8a71f7..e60f711b9 100644--- a/cyberdrop_dl/config_definitions/global_settings.py+++ b/cyberdrop_dl/config_definitions/global_settings.py@@ -1,14 +1,12 @@-import refrom datetime import timedeltafrom pydantic import BaseModel, ByteSize, Field, NonNegativeFloat, PositiveInt, field_serializer, field_validatorfrom yarl import URL-from .custom_types import AliasModel, HttpURL, NonEmptyStr+from cyberdrop_dl.config_definitions.pydantic.validators import parse_duration_to_timedelta++from .pydantic.custom_types import AliasModel, HttpURL, NonEmptyStr-DATE_PATTERN = re.compile(- r"(\d+)\s*(second|seconds|minute|minutes|hour|hours|day|days|week|weeks|month|months|year|years)", re.IGNORECASE-)MIN_REQUIRED_FREE_SPACE = ByteSize._validate("512MB", "")DEFAULT_REQUIRED_FREE_SPACE = ByteSize._validate("5GB", "")@@ -76,39 +74,7 @@ class RateLimitingOptions(BaseModel):for `int`, value is assummed as `days`"""- if not input_date:- return 0- parsed_timedelta = input_date- if isinstance(input_date, int):- parsed_timedelta = timedelta(days=input_date)- if isinstance(input_date, str):- time_str = input_date.casefold()- matches: list[str] = re.findall(DATE_PATTERN, time_str)- seen_units = set()- time_dict = {"days": 0}-- for value, unit in matches:- value = int(value)- unit = unit.lower()- normalized_unit = unit.rstrip("s")- plural_unit = normalized_unit + "s"- if normalized_unit in seen_units:- raise ValueError(f"Duplicate time unit detected: '{unit}' conflicts with another entry.")- seen_units.add(normalized_unit)-- if "day" in unit:- time_dict["days"] += value- elif "month" in unit:- time_dict["days"] += value * 30- elif "year" in unit:- time_dict["days"] += value * 365- else:- time_dict[plural_unit] = value-- if matches:- parsed_timedelta = timedelta(**time_dict)-- return parsed_timedelta+ return parse_duration_to_timedelta(input_date)class UIOptions(BaseModel):diff --git a/cyberdrop_dl/config_definitions/custom_types.py b/cyberdrop_dl/config_definitions/pydantic/custom_types.pysimilarity index 100%rename from cyberdrop_dl/config_definitions/custom_types.pyrename to cyberdrop_dl/config_definitions/pydantic/custom_types.pydiff --git a/cyberdrop_dl/config_definitions/pydantic/validators.py b/cyberdrop_dl/config_definitions/pydantic/validators.pynew file mode 100644index 000000000..b4f17d6c8--- /dev/null+++ b/cyberdrop_dl/config_definitions/pydantic/validators.py@@ -0,0 +1,51 @@+import re+from datetime import timedelta++DATE_PATTERN = re.compile(+ r"(\d+)\s*(second|seconds|minute|minutes|hour|hours|day|days|week|weeks|month|months|year|years)", re.IGNORECASE+)+++def parse_duration_to_timedelta(input_date: timedelta | str | int) -> 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 not input_date:+ return 0+ parsed_timedelta = input_date+ if isinstance(input_date, int):+ parsed_timedelta = timedelta(days=input_date)+ if isinstance(input_date, str):+ time_str = input_date.casefold()+ matches: list[str] = re.findall(DATE_PATTERN, time_str)+ seen_units = set()+ time_dict = {"days": 0}++ for value, unit in matches:+ value = int(value)+ unit = unit.lower()+ normalized_unit = unit.rstrip("s")+ plural_unit = normalized_unit + "s"+ if normalized_unit in seen_units:+ raise ValueError(f"Duplicate time unit detected: '{unit}' conflicts with another entry.")+ seen_units.add(normalized_unit)++ if "day" in unit:+ time_dict["days"] += value+ elif "month" in unit:+ time_dict["days"] += value * 30+ elif "year" in unit:+ time_dict["days"] += value * 365+ else:+ time_dict[plural_unit] = value++ if matches:+ parsed_timedelta = timedelta(**time_dict)++ return parsed_timedeltadiff --git a/cyberdrop_dl/managers/path_manager.py b/cyberdrop_dl/managers/path_manager.pyindex ebce150cc..a957dd4d2 100644--- a/cyberdrop_dl/managers/path_manager.py+++ b/cyberdrop_dl/managers/path_manager.py@@ -6,6 +6,7 @@ from pathlib import Pathfrom typing import TYPE_CHECKINGfrom cyberdrop_dl.utils import constants+from cyberdrop_dl.utils.utilities import purge_dir_treeif TYPE_CHECKING:from cyberdrop_dl.managers.manager import Manager@@ -84,16 +85,20 @@ class PathManager:self.input_file = self.replace_config_in_path(settings_data.files.input_file)self.history_db = self.cache_folder / "cyberdrop.db"- self._set_output_filenames()self.log_folder.mkdir(parents=True, exist_ok=True)++ now = datetime.now()+ self._set_output_filenames(now)+ self._delete_logs_and_folders(now)self._create_output_folders()if not self.input_file.is_file():self.input_file.touch(exist_ok=True)self.history_db.touch(exist_ok=True)- def _set_output_filenames(self) -> None:- current_time_iso = datetime.now().strftime("%Y%m%d_%H%M%S")+ def _set_output_filenames(self, now) -> None:+ current_time_file_iso = now.strftime("%Y%m%d_%H%M%S")+ current_time_folder_iso = now.strftime("%Y_%m_%d")log_settings_config = self.manager.config_manager.settings_data.logslog_files: dict[str, Path] = log_settings_config.model_dump()@@ -101,7 +106,11 @@ class PathManager:if model_name not in self._logs_model_names:continueif log_settings_config.rotate_logs:- log_file = log_file.parent / f"{log_file.stem}__{current_time_iso}{log_file.suffix}"+ log_file = (+ log_file.parent+ / current_time_folder_iso+ / f"{log_file.stem}_{current_time_file_iso}{log_file.suffix}"+ )log_files[model_name] = log_filelog_settings_config = log_settings_config.model_copy(update=log_files)@@ -110,6 +119,15 @@ class PathManager:internal_name = f"{model_name.replace('_log','')}_log"setattr(self, internal_name, self.log_folder / getattr(log_settings_config, model_name))+ def _delete_logs_and_folders(self, now):+ if self.manager.config_manager.settings_data.logs.logs_expire_after:+ for file in set(self.log_folder.rglob("*.log")) | set(self.log_folder.rglob("*.csv")):+ if (+ now - datetime.fromtimestamp(Path(file).stat().st_ctime)+ ) > self.manager.config_manager.settings_data.logs.logs_expire_after:+ file.unlink(missing_ok=True)+ purge_dir_tree(self.log_folder)+def _create_output_folders(self):for model_name in self._logs_model_names:internal_name = f"{model_name.replace('_log','')}_log"diff --git a/cyberdrop_dl/utils/args.py b/cyberdrop_dl/utils/args.pyindex f0bcfcc0b..679aa4dde 100644--- a/cyberdrop_dl/utils/args.py+++ b/cyberdrop_dl/utils/args.py@@ -11,7 +11,7 @@ from pydantic import BaseModel, Field, ValidationError, computed_field, field_vafrom cyberdrop_dl import __version__from cyberdrop_dl.config_definitions import ConfigSettings, GlobalSettings-from cyberdrop_dl.config_definitions.custom_types import AliasModel, HttpURL+from cyberdrop_dl.config_definitions.pydantic.custom_types import AliasModel, HttpURLfrom cyberdrop_dl.utils.yaml import handle_validation_errorif TYPE_CHECKING:diff --git a/docs/reference/configuration-options/settings/logs.md b/docs/reference/configuration-options/settings/logs.mdindex 09b6794ac..67c4a594d 100644--- a/docs/reference/configuration-options/settings/logs.md+++ b/docs/reference/configuration-options/settings/logs.md@@ -76,8 +76,36 @@ Example:If enabled, Cyberdrop-DL will add the current date and time as a suffix to each log file, in the format `YYMMDD_HHMMSS`+Every log file will be created inside a sub folder with the current date+This will prevent overriding old log files+++## `logs_expire_after`++| Type | Default |+|-------------------|----------|+| `timedelta` or `null`| `null`|++With `rotate_logs` enabled, this setting specifies the retention period for log files before they are deleted++- 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 `null` value will disable automatic delection of logs+++{% hint style="warning" %}+Any `.log` or `.csv` file within `log_folder` will be deleted, even if CDL did not create them+{% endhint %}++{% hint style="info" %}+Log files with an absolute path not relative to `log_folder` will never be deleted+{% endhint %}+++## `log_line_width`| Type | Default | Restrictions |