Bulk asynchronous downloader for multiple file hosts
Python asynciobunkrcyberdropdownloaderdropboxfilestergofilegoogle-drivemediafiremegamega-nzonedrivepatreonpawchivepinterestpixeldraintransfer-ittwitchtwittervk
refactor: remove deprecated args (#1966)
NTFSvolume9281c163e61b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 63c2470b2..14df5c8e5 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -33,7 +33,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed- Video metadata extraction (Spankbang)-- Crashing when `--json` option is used+- Crashing when `--dump-json` option is used## [9.15.0] - 2026-06-10@@ -52,7 +52,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0> If you has ever used a Pixeldrain API key with `cyberdrop-dl-pacthed` version >=8.5.0, you should consider them compromised and disable them.>-> See: [GHSA-f5pf-q7c7-m3vv](https://github.com/Cyberdrop-DL/cyberdrop-dl/security/advisories/GHSA-f5pf-q7c7-m3vv)+> See: [GHSA-f5pf-q7c7-m3vv (CVE-2026-54254)](https://github.com/Cyberdrop-DL/cyberdrop-dl/security/advisories/GHSA-f5pf-q7c7-m3vv)### Addeddiff --git a/cyberdrop_dl/cli/__init__.py b/cyberdrop_dl/cli/__init__.pyindex bef29d25c..923b9380f 100644--- a/cyberdrop_dl/cli/__init__.py+++ b/cyberdrop_dl/cli/__init__.py@@ -1,11 +1,9 @@-import datetime-from collections.abc import Iterablefrom pathlib import Path-from typing import Annotated, Any, Literal, Self+from typing import Annotated, Literalfrom cyclopts import Parameterfrom cyclopts.core import App-from pydantic import BaseModel, Field, computed_field, field_validator, model_validator+from pydantic import BaseModel, Field, computed_field, field_validatorfrom cyberdrop_dl import __version__from cyberdrop_dl.models.types import HttpURL@@ -22,14 +20,6 @@ class CLIargs(BaseModel):default=None,description="AppData folder path",)- completed_after: datetime.date | None = Field(- default=None,- description="only retry downloads that were completed on or after this date",- )- completed_before: datetime.date | None = Field(- default=None,- description="only retry downloads that were completed on or before this date",- )config_file: Path | None = Field(default=None,@@ -62,10 +52,7 @@ class CLIargs(BaseModel):default=None,description="Use this target as impersonation for all scrape requests",)- max_items_retry: int = Field(- default=0,- description="max number of links to retry",- )+portrait: bool = Field(default=False,description="force CDL to run with a vertical layout",@@ -74,41 +61,18 @@ class CLIargs(BaseModel):default=True,description="show stats report at the end of a run",)- retry_all: bool = Field(- default=False,- description="retry all downloads",- )- retry_failed: bool = Field(- default=False,- description="retry failed downloads",- )- retry_maintenance: bool = Field(- default=False,- description="retry download of maintenance files (bunkr). Requires files to be hashed",- )ui: UIOptions = Field(default=UIOptions.FULLSCREEN,description="DISABLED, ACTIVITY, SIMPLE or FULLSCREEN",)- @property- def retry_any(self) -> bool:- return any((self.retry_all, self.retry_failed, self.retry_maintenance))-@propertydef fullscreen_ui(self) -> bool:return self.ui == UIOptions.FULLSCREEN@computed_fielddef __computed__(self) -> dict[str, bool]:- return {"retry_any": self.retry_any, "fullscreen_ui": self.fullscreen_ui}-- @model_validator(mode="after")- def mutually_exclusive(self) -> Self:- group1 = [self.links, self.retry_all, self.retry_failed, self.retry_maintenance]- msg1 = "`--links`, '--retry-all', '--retry-maintenace' and '--retry-failed' are mutually exclusive"- _check_mutually_exclusive(group1, msg1)- return self+ return {"fullscreen_ui": self.fullscreen_ui}@field_validator("ui", mode="before")@classmethod@@ -116,11 +80,6 @@ class CLIargs(BaseModel):return value.lower()-def _check_mutually_exclusive(group: Iterable[Any], msg: str) -> None:- if sum(1 for value in group if value) >= 2:- raise ValueError(msg)--app = App(name="cyberdrop-dl",help="Bulk asynchronous downloader for multiple file hosts",diff --git a/cyberdrop_dl/cli/download.py b/cyberdrop_dl/cli/download.pyindex 13d247773..56c625e90 100644--- a/cyberdrop_dl/cli/download.py+++ b/cyberdrop_dl/cli/download.py@@ -71,14 +71,11 @@ async def _post_runtime(manager: Manager) -> None:file_hashes = await manager.hasher.run()await manager.deduper.run(file_hashes)- if manager.config.settings.sorting.sort_downloads and not manager.cli_args.retry_any:+ if manager.config.settings.sorting.sort_downloads:await manager.sorter.run()check_partials_and_empty_folders(manager.config)- if manager.config.settings.runtime_options.update_last_forum_post:- await manager.logs.update_last_forum_post(manager.config.settings.files.input_file)-def _main(manager: Manager) -> None:from cyberdrop_dl import aio, program_ui@@ -113,10 +110,8 @@ def download(appdata = AppData.from_path(cli.appdata_folder) if cli.appdata_folder else AppData.default()config = Config.create(appdata, cli.config_file).update(config)- if cli.retry_all or cli.retry_maintenance:- config.settings.runtime_options.ignore_history = True- if not cli.fullscreen_ui or cli.retry_any or cli.config_file or config.settings.sorting.sort_downloads:+ if not cli.fullscreen_ui or cli.config_file or config.settings.sorting.sort_downloads:cli.download = Truemanager = Manager(cli, appdata, config)diff --git a/cyberdrop_dl/clients/downloads.py b/cyberdrop_dl/clients/downloads.pyindex 51dc8a7b7..f59c3a43a 100644--- a/cyberdrop_dl/clients/downloads.py+++ b/cyberdrop_dl/clients/downloads.py@@ -259,8 +259,6 @@ class DownloadClient:def get_download_dir(self, media_item: MediaItem) -> Path:"""Returns the download directory for the media item."""download_folder = media_item.download_folder- if self.manager.cli_args.retry_any:- return download_folderif self.manager.config.settings.download_options.block_download_sub_folders:while download_folder.parent != self.manager.config.settings.files.download_folder:diff --git a/cyberdrop_dl/clients/http.py b/cyberdrop_dl/clients/http.pyindex 1727bf888..d15f259c3 100644--- a/cyberdrop_dl/clients/http.py+++ b/cyberdrop_dl/clients/http.py@@ -103,7 +103,7 @@ class HTTPClient:@staticmethoddef from_manager(manager: Manager) -> HTTPClient:client = HTTPClient(config=manager.config, impersonate=manager.cli_args.impersonate)- if manager.config.settings.files.save_pages_html or manager.config.settings.files.dump_responses:+ if manager.config.settings.files.dump_responses:client.request_done_callback = manager.logs.write_responsereturn clientdiff --git a/cyberdrop_dl/config/auth.py b/cyberdrop_dl/config/auth.pyindex 95245bae6..7b6f6e183 100644--- a/cyberdrop_dl/config/auth.py+++ b/cyberdrop_dl/config/auth.py@@ -1,37 +1,28 @@from cyclopts import Parameter-from pydantic import BaseModel, Field+from pydantic import Field+from cyberdrop_dl.models import AliasModel-class ApiKeyAuth(BaseModel):++class ApiKeyAuth(AliasModel):api_key: str = ""-class EmailAuth(BaseModel):+class EmailAuth(AliasModel):email: str = ""password: str = ""-class ImgurAuth(BaseModel):- client_id: str = ""---class JDownloaderAuth(BaseModel):+class JDownloaderAuth(AliasModel):username: str = ""password: str = ""device: str = ""-class KemonoAuth(BaseModel):- session: str = ""--@Parameter(show=False)-class AuthSettings(BaseModel, defer_build=True):- coomer: KemonoAuth = Field(default_factory=KemonoAuth)+class AuthSettings(AliasModel):gofile: ApiKeyAuth = Field(default_factory=ApiKeyAuth)- imgur: ImgurAuth = Field(default_factory=ImgurAuth)jdownloader: JDownloaderAuth = Field(default_factory=JDownloaderAuth)- kemono: KemonoAuth = Field(default_factory=KemonoAuth)meganz: EmailAuth = Field(default_factory=EmailAuth)pixeldrain: ApiKeyAuth = Field(default_factory=ApiKeyAuth)realdebrid: ApiKeyAuth = Field(default_factory=ApiKeyAuth)diff --git a/cyberdrop_dl/config/settings.py b/cyberdrop_dl/config/settings.pyindex 41770388e..b1425063b 100644--- a/cyberdrop_dl/config/settings.py+++ b/cyberdrop_dl/config/settings.py@@ -5,7 +5,7 @@ import refrom datetime import date, datetime, timedeltafrom functools import cached_propertyfrom pathlib import Path-from typing import Annotated, Any, Literal, Self+from typing import Annotated, Any, Literal, Self, overridefrom cyclopts import Parameterfrom pydantic import BaseModel, ByteSize, Field, NonNegativeInt, PrivateAttr, field_validator@@ -15,7 +15,6 @@ from cyberdrop_dl.constants import (DEFAULT_DOWNLOAD_STORAGE,LOGS_DATE_FORMAT,LOGS_DATETIME_FORMAT,- Browser,Hashing,)from cyberdrop_dl.models import AliasModel, AppriseURL, SettingsGroup@@ -47,14 +46,11 @@ _SORTING_COMMON_FIELDS = {class DownloadOptions(SettingsGroup):block_download_sub_folders: bool = False- disable_download_attempt_limit: bool = Falsedisable_file_timestamps: bool = Falseinclude_album_id_in_folder_name: bool = Falseinclude_thread_id_in_folder_name: bool = Falsemaximum_number_of_children: ListNonNegativeInt = []remove_domains_from_folder_names: bool = False- remove_generated_id_from_filenames: bool = False- scrape_single_forum_post: bool = Falseseparate_posts_format: NonEmptyStr = "{default}"separate_posts: bool = Falseskip_download_mark_completed: bool = False@@ -75,14 +71,12 @@ class Files(SettingsGroup):)dump_json: Annotated[bool, Parameter(alias="-j")] = Field(default=False, validation_alias="j")input_file: Annotated[Path, Parameter(alias="-i")] = Field(default=Path("URLs.txt"), validation_alias="i")- save_pages_html: bool = Falsedump_responses: bool = False"""Save text/HTML/JSON responses to disk (flaresolverr responses are excluded)"""class Logs(SettingsGroup): # noqa: PLW1641download_error_urls: LogPath = Path("Download_Error_URLs.csv")- last_forum_post: LogPath = Path("Last_Scraped_Forum_Posts.csv")log_folder: Path = DEFAULT_APP_STORAGE / "Logs"logs_expire_after: timedelta | None = Nonemain_log: MainLogPath = Path("downloader.log")@@ -289,7 +283,6 @@ class RuntimeOptions(SettingsGroup):skip_check_for_empty_folders: bool = Falseskip_check_for_partial_files: bool = Falseslow_download_speed: ByteSizeSerilized = ByteSize(0)- update_last_forum_post: bool = True@field_validator("log_level", "console_log_level", mode="before")@classmethod@@ -374,23 +367,37 @@ class Sorting(SettingsGroup):return value-class BrowserCookies(SettingsGroup):- auto_import: bool = False- browser: Browser | None = Browser.firefox- sites: list[str] = Field(default_factory=list)+class Cookies(SettingsGroup):+ cookies: Path | None = None+ "File/folder to import cookies from (.txt Netscape files)"class DupeCleanup(SettingsGroup):- add_md5_hash: bool = False- add_sha256_hash: bool = False+ hashes: tuple[Literal["xxh128", "md5", "sha256"], ...] = "xxh128", "md5", "sha256"auto_dedupe: bool = Truehashing: Hashing = Hashing.IN_PLACEsend_deleted_to_trash: bool = True+ _extra_hashes: tuple[Literal["md5", "sha256"], ...] = ()++ @override+ def model_post_init(self, *_) -> None:+ self.re_compute()++ def re_compute(self) -> None:+ hashes = set(self.hashes)+ if (xxhash := "xxh128") not in hashes:+ self.hashes = xxhash, *hashes+ hashes.discard(xxhash)+ self._extra_hashes = tuple(sorted(hashes)) # pyright: ignore[reportAttributeAccessIssue]++ @property+ def extra_hashes(self) -> tuple[Literal["md5", "sha256"], ...]:+ return self._extra_hashes@Parameter(name="*")class ConfigSettings(AliasModel):- browser_cookies: BrowserCookies = Field(default_factory=BrowserCookies)+ cookies: Cookies = Field(default_factory=Cookies)download_options: DownloadOptions = Field(default_factory=DownloadOptions)dupe_cleanup_options: DupeCleanup = Field(default_factory=DupeCleanup)file_size_limits: FileSizeLimits = Field(default_factory=FileSizeLimits)diff --git a/cyberdrop_dl/crawlers/_forum.py b/cyberdrop_dl/crawlers/_forum.pyindex 4e6c7e7d2..c35280fb7 100644--- a/cyberdrop_dl/crawlers/_forum.py+++ b/cyberdrop_dl/crawlers/_forum.py@@ -197,11 +197,6 @@ class MessageBoardCrawler(Crawler, is_abc=True):login_url = self.PRIMARY_URL / "login"await self.login(login_url)- @final- @property- def scrape_single_forum_post(self) -> bool:- return self.config.settings.download_options.scrape_single_forum_post-@final@propertydef max_thread_depth(self) -> int:@@ -319,12 +314,6 @@ class MessageBoardCrawler(Crawler, is_abc=True):new_scrape_item.part_of_album = Trueawait self.handle_file(link, new_scrape_item, filename, ext)- @final- async def _write_last_forum_post(self, thread_url: AbsoluteHttpURL, last_post_url: AbsoluteHttpURL | None) -> None:- if not last_post_url or last_post_url == thread_url:- return- self.manager.logs.write_last_post_log(last_post_url)-# TODO: Move this to the base crawler# TODO: Define an unified workflow for crawlers to perform and check login@final@@ -371,7 +360,7 @@ class HTMLMessageBoardCrawler(MessageBoardCrawler, is_abc=True):Concrete classes SHOULD define `ATTACHMENT_HOSTS` if internal images of the site are stored on servers with a different domain"""- IGNORE_EMBEDED_IMAGES_SRC = True+ IGNORE_EMBEDED_IMAGES_SRC: ClassVar[bool] = TrueSELECTORS: ClassVar[MessageBoardSelectors]POST_URL_PART_NAME: ClassVar[str]PAGE_URL_PART_NAME: ClassVar[str]@@ -385,7 +374,7 @@ class HTMLMessageBoardCrawler(MessageBoardCrawler, is_abc=True):assert getattr(cls, field_name, None), f"Subclass {cls.__name__} must override: {field_name}"def __post_init__(self) -> None:- self.scraped_threads = set()+ self.scraped_threads: set[AbsoluteHttpURL] = set()@classmethoddef is_thumbnail(cls, link: AbsoluteHttpURL) -> bool:@@ -412,16 +401,11 @@ class HTMLMessageBoardCrawler(MessageBoardCrawler, is_abc=True):returnscrape_item.parent_threads.add(thread.url)- if self.scrape_single_forum_post and not thread.post_id:- msg = "`--scrape-single-forum-post` is `True`, but the provided URL has no post id"- raise ScrapeError("User Error", msg)-self.scraped_threads.add(thread.url)await self._thread(scrape_item, thread)async def _thread(self, scrape_item: ScrapeItem, thread: ThreadProtocol) -> None:title: str = ""- last_post_url = thread.urlasync for soup in self.thread_pager(scrape_item):if not title:try:@@ -431,37 +415,19 @@ class HTMLMessageBoardCrawler(MessageBoardCrawler, is_abc=True):raisescrape_item.append_folders(title)- continue_scraping, last_post_url = self._thread_page(scrape_item, thread, soup)- if not continue_scraping:- break+ self._thread_page(scrape_item, thread, soup)- await self._write_last_forum_post(thread.url, last_post_url)-- def _thread_page(- self, scrape_item: ScrapeItem, thread: ThreadProtocol, soup: BeautifulSoup- ) -> tuple[bool, AbsoluteHttpURL]:- continue_scraping = False- post_url = thread.url+ def _thread_page(self, scrape_item: ScrapeItem, thread: ThreadProtocol, soup: BeautifulSoup) -> None:for article in soup.select(self.SELECTORS.posts.article):current_post = ForumPost.new(article, self.SELECTORS.posts)- continue_scraping, scrape_this_post = check_post_id(- thread.post_id,- current_post.id,- scrape_single_forum_post=self.scrape_single_forum_post,- )- if scrape_this_post:- post_url = self.make_post_url(thread, current_post.id)- new_scrape_item = scrape_item.create_new(thread.url, add_parent=post_url)- new_scrape_item.uploaded_at = current_post.timestamp- self.create_task(self.post(new_scrape_item, current_post))- try:- scrape_item.add_children()- except MaxChildrenError:- break+ if thread.post_id and current_post.id < thread.post_id:+ continue- if not continue_scraping:- break- return continue_scraping, post_url+ post_url = self.make_post_url(thread, current_post.id)+ new_scrape_item = scrape_item.create_new(thread.url, add_parent=post_url)+ new_scrape_item.uploaded_at = current_post.timestamp+ self.create_task(self.post(new_scrape_item, current_post))+ scrape_item.add_children()@error_handling_wrapperasync def post(self, scrape_item: ScrapeItem, post: ForumPostProtocol) -> None:@@ -686,26 +652,6 @@ def is_confirmation_link(link: AbsoluteHttpURL) -> bool:)-def check_post_id(- init_post_id: int | None,- current_post_id: int,- *,- scrape_single_forum_post: bool,-) -> tuple[bool, bool]:- """Checks if the program should scrape the current post.-- Returns (continue_scraping, scrape_this_post)"""- if init_post_id:- if init_post_id > current_post_id:- return (True, False)- if init_post_id == current_post_id:- return (not scrape_single_forum_post, True)- return (not scrape_single_forum_post, not scrape_single_forum_post)-- assert not scrape_single_forum_post # We should have raised an exception earlier- return True, True--def pre_process_child(link_str: str, *, embeds: bool = False) -> str | None:assert isinstance(link_str, str)if embeds:diff --git a/cyberdrop_dl/crawlers/coomer.py b/cyberdrop_dl/crawlers/coomer.pyindex 0720b99d9..6c80cfc92 100644--- a/cyberdrop_dl/crawlers/coomer.py+++ b/cyberdrop_dl/crawlers/coomer.py@@ -13,7 +13,3 @@ class CoomerCrawler(KemonoBaseCrawler):API_ENTRYPOINT: ClassVar[AbsoluteHttpURL] = AbsoluteHttpURL("https://coomer.st/api/v1")SERVICES: ClassVar[tuple[str, ...]] = "onlyfans", "fansly", "candfans"OLD_DOMAINS: ClassVar[tuple[str, ...]] = "coomer.party", "coomer.su"-- @property- def session_cookie(self) -> str:- return self.config.auth.coomer.sessiondiff --git a/cyberdrop_dl/crawlers/discourse/__init__.py b/cyberdrop_dl/crawlers/discourse/__init__.pyindex 6fbc65c82..633a3e137 100644--- a/cyberdrop_dl/crawlers/discourse/__init__.py+++ b/cyberdrop_dl/crawlers/discourse/__init__.py@@ -12,7 +12,6 @@ from bs4 import BeautifulSoupfrom pydantic import BaseModelfrom cyberdrop_dl.crawlers._forum import MessageBoardCrawler-from cyberdrop_dl.exceptions import MaxChildrenErrorfrom cyberdrop_dl.url_objects import AbsoluteHttpURLfrom cyberdrop_dl.utils import css, error_handling_wrapperfrom cyberdrop_dl.utils.dates import to_timestamp@@ -100,21 +99,11 @@ class DiscourseCrawler(MessageBoardCrawler, is_generic=True):@error_handling_wrapperasync def process_posts(self, scrape_item: ScrapeItem, topic: Topic) -> None:- last_post_id = Noneasync for post in self.iter_posts(topic):new_scrape_item = scrape_item.create_child(self.PRIMARY_URL / post.path.removeprefix("/"))new_scrape_item.uploaded_at = to_timestamp(post.created_at)await self.post(new_scrape_item, post)- last_post_id = post.id- try:- scrape_item.add_children()- except MaxChildrenError:- break-- if last_post_id:- topic_url = self.PRIMARY_URL / topic.path.removeprefix("/")- post_url = topic_url / str(last_post_id)- await self._write_last_forum_post(topic_url, post_url)+ scrape_item.add_children()async def iter_posts(self, topic: Topic) -> AsyncIterable[AvailablePost]:for offset in itertools.count(topic.init_post_number - 1, _MAX_POSTS_PER_REQUEST):@@ -124,8 +113,6 @@ class DiscourseCrawler(MessageBoardCrawler, is_generic=True):stream = await self.make_request(PostStream, f"t/{topic.id}/posts.json", {"post_ids[]": remaining})for post in stream.posts:yield post- if topic.init_post_number != 1 and self.scrape_single_forum_post:- return@error_handling_wrapperasync def post(self, scrape_item: ScrapeItem, /, post: AvailablePost) -> None: # pyright: ignore[reportIncompatibleMethodOverride]diff --git a/cyberdrop_dl/crawlers/kemono.py b/cyberdrop_dl/crawlers/kemono.pyindex abb6c6a2b..07c98fd9d 100644--- a/cyberdrop_dl/crawlers/kemono.py+++ b/cyberdrop_dl/crawlers/kemono.py@@ -206,10 +206,6 @@ class KemonoBaseCrawler(Crawler, is_abc=True):self.__discord_servers_locks: dict[str, asyncio.Lock] = defaultdict(asyncio.Lock)self.__ad_posts: list[str] = []- @property- def session_cookie(self) -> str:- return ""-@propertydef ignore_content(self) -> bool:return self.config.settings.ignore_options.ignore_coomer_post_content@@ -320,13 +316,14 @@ class KemonoBaseCrawler(Crawler, is_abc=True):@fallback_if_no_api@error_handling_wrapperasync def favorites(self, scrape_item: ScrapeItem, type_: str) -> None:- if not self.session_cookie:- msg = "No session cookie found in the config file, cannot scrape favorites"+ session_cookie = self.get_cookie_value("session")+ if not session_cookie:+ msg = "No session cookie found, cannot scrape favorites"raise ScrapeError(401, msg)title = f"My favorite {type_}s"scrape_item.setup_as_profile(self.create_title(title))- self.update_cookies({"session": self.session_cookie})+ self.update_cookies({"session": session_cookie})query_url = (self.API_ENTRYPOINT / "account/favorites").with_query(type=type_)resp: list[dict[str, Any]] = await self.__api_request(query_url)self.update_cookies({"session": ""})@@ -613,10 +610,6 @@ class KemonoCrawler(KemonoBaseCrawler):)OLD_DOMAINS: ClassVar[tuple[str, ...]] = "kemono.party", "kemono.su"- @property- def session_cookie(self) -> str:- return self.config.auth.kemono.session-def _thumbnail_to_src(og_url: AbsoluteHttpURL) -> AbsoluteHttpURL:url = og_url.with_path(og_url.path.replace("/thumbnails/", "/").replace("/thumbnail/", "/"))diff --git a/cyberdrop_dl/crawlers/vbulletin/__init__.py b/cyberdrop_dl/crawlers/vbulletin/__init__.pyindex e5b1f0f99..72cc6889f 100644--- a/cyberdrop_dl/crawlers/vbulletin/__init__.py+++ b/cyberdrop_dl/crawlers/vbulletin/__init__.py@@ -6,7 +6,7 @@ from typing import TYPE_CHECKING, Any, ClassVar, overridefrom xml.etree import ElementTree as ETfrom cyberdrop_dl.crawlers.xenforo.xenforo import XenforoCrawler-from cyberdrop_dl.exceptions import MaxChildrenError, ScrapeError+from cyberdrop_dl.exceptions import ScrapeErrorfrom cyberdrop_dl.utils import error_handling_wrapperif TYPE_CHECKING:@@ -85,10 +85,7 @@ class vBulletinCrawler(XenforoCrawler, is_abc=True): # noqa: N801@overrideasync def _thread(self, scrape_item: ScrapeItem, thread: Thread) -> None: # pyright: ignore[reportIncompatibleMethodOverride]title: str = ""- if thread.post_id and self.scrape_single_forum_post:- api_url = self.VBULLETIN_API_ENDPOINT.with_query({self.VBULLETIN_POST_QUERY_PARAM: str(thread.post_id)})- else:- api_url = self.VBULLETIN_API_ENDPOINT.with_query({self.VBULLETIN_THREAD_QUERY_PARAM: str(thread.id)})+ api_url = self.VBULLETIN_API_ENDPOINT.with_query({self.VBULLETIN_THREAD_QUERY_PARAM: str(thread.id)})root_xml = _parse_xml(await self.request_text(api_url))if (thread_element := root_xml.find("thread")) is not None:@@ -105,7 +102,6 @@ class vBulletinCrawler(XenforoCrawler, is_abc=True): # noqa: N801else:posts = root_xml.iter("post")- last_post_id = thread.post_idfor element in posts:post = Post.new(element)if thread.post_id and thread.post_id > post.id:@@ -114,15 +110,7 @@ class vBulletinCrawler(XenforoCrawler, is_abc=True): # noqa: N801thread.url.update_query({self.VBULLETIN_POST_QUERY_PARAM: str(post.id)}))await self.post(new_scrape_item, post)- last_post_id = post.id- try:- scrape_item.add_children()- except MaxChildrenError:- break-- if last_post_id:- last_post_url = thread.url.update_query({self.VBULLETIN_POST_QUERY_PARAM: str(last_post_id)})- await self._write_last_forum_post(thread.url, last_post_url)+ scrape_item.add_children()@override@error_handling_wrapperdiff --git a/cyberdrop_dl/csv_logs.py b/cyberdrop_dl/csv_logs.pyindex db0873948..e4a04830b 100644--- a/cyberdrop_dl/csv_logs.py+++ b/cyberdrop_dl/csv_logs.py@@ -10,7 +10,6 @@ from typing import TYPE_CHECKING, Any, Selffrom cyberdrop_dl import constantsfrom cyberdrop_dl.exceptions import get_origin-from cyberdrop_dl.logs import log_spacerfrom cyberdrop_dl.utils import jsonfrom cyberdrop_dl.utils.filepath import sanitize_filename@@ -33,7 +32,6 @@ _CSV_DELIMITER = ","@dataclasses.dataclass(slots=True, kw_only=True)class CSVFiles:main_log: Path- last_post_log: Pathunsupported_urls_log: Pathdownload_error_log: Pathscrape_error_log: Path@@ -64,7 +62,6 @@ class CSVLogsManager:def from_manager(cls, manager: Manager) -> Self:files = CSVFiles(main_log=manager.config.settings.logs.main_log,- last_post_log=manager.config.settings.logs.last_forum_post,unsupported_urls_log=manager.config.settings.logs.unsupported_urls,download_error_log=manager.config.settings.logs.download_error_urls,scrape_error_log=manager.config.settings.logs.scrape_error_urls,@@ -110,10 +107,6 @@ class CSVLogsManager:await asyncio.to_thread(write)- def write_last_post_log(self, url: URL) -> None:- """Writes to the last post log."""- _ = self.task_group.create_task(self._write_to_csv(self.files.last_post_log, url=url))-def write_unsupported(self, url: URL, origin: URL | None = None) -> None:"""Writes to the unsupported urls log."""_ = self.task_group.create_task(self._write_to_csv(self.files.unsupported_urls_log, url=url, origin=origin))@@ -153,68 +146,6 @@ class CSVLogsManager:))- async def update_last_forum_post(self, input_file: Path) -> None:- """Updates the last forum post."""-- def update() -> None:- if input_file.is_file() and self.files.last_post_log.is_file():- _update_last_forum_post(input_file, self.files.last_post_log)-- await asyncio.to_thread(update)---def _update_last_forum_post(input_file: Path, last_post_log: Path) -> None: # noqa: C901- log_spacer()- logger.info("Updating Last Forum Posts...\n")-- current_urls, current_base_urls, new_urls, new_base_urls = [], [], [], []- try:- with input_file.open(encoding="utf8") as f:- for line in f:- url = base_url = line.strip().removesuffix("/")-- if "https" in url and "/post-" in url:- base_url = url.rsplit("/post", 1)[0]-- # only keep 1 url of the same thread- if base_url not in current_base_urls:- current_urls.append(url)- current_base_urls.append(base_url)-- except UnicodeDecodeError:- logger.exception("Unable to read input file, skipping update_last_forum_post")- return-- with last_post_log.open(encoding="utf8") as f:- reader = csv.DictReader(f.readlines())- for row in reader:- new_url = base_url = row["url"].strip().removesuffix("/")-- if "https" in new_url and "/post-" in new_url:- base_url = new_url.rsplit("/post", 1)[0]-- # only keep 1 url of the same thread- if base_url not in new_base_urls:- new_urls.append(new_url)- new_base_urls.append(base_url)-- updated_urls = current_urls.copy()- for new_url, base in zip(new_urls, new_base_urls, strict=False):- if base in current_base_urls:- index = current_base_urls.index(base)- old_url = current_urls[index]- if old_url == new_url:- continue- logger.info(f"Updating {base}\n {old_url = }\n {new_url = }")- updated_urls[index] = new_url-- if updated_urls == current_urls:- logger.info("No URLs updated")- return-- with input_file.open("w", encoding="utf8") as f:- f.write("\n".join(updated_urls))-def _write_resp_to_disk(folder: Path,diff --git a/cyberdrop_dl/database/hash.py b/cyberdrop_dl/database/hash.pyindex a00e9eef4..626f012c0 100644--- a/cyberdrop_dl/database/hash.py+++ b/cyberdrop_dl/database/hash.py@@ -161,26 +161,3 @@ class HashTable(table.Table):logger.exception("Error inserting/updating record")return Falsereturn True-- async def get_all_unique_hashes(self, hash_type: str | None = None) -> list[str]:- """Retrieves a list of hashes-- Args:- hash_value: The hash value to search for.- hash_type: The type of hash[optional]-- Returns:- A list of (folder, filename) tuples, or an empty list if no matches found.- """- if hash_type:- query, params = "SELECT DISTINCT hash FROM hash WHERE hash_type =?", (hash_type,)-- else:- query, params = "SELECT DISTINCT hash FROM hash", ()- try:- cursor = await self.db_conn.execute(query, params)- rows = await cursor.fetchall()- return [row[0] for row in rows]- except Exception:- logger.exception("Error retrieving folder and filename")- return []diff --git a/cyberdrop_dl/database/history.py b/cyberdrop_dl/database/history.pyindex ecd35c519..9b854ab5a 100644--- a/cyberdrop_dl/database/history.py+++ b/cyberdrop_dl/database/history.py@@ -10,7 +10,6 @@ from cyberdrop_dl.database import tablefrom cyberdrop_dl.database.definitions import CREATE_HISTORY, CREATE_MEDIA_INDEXif TYPE_CHECKING:- import datetimefrom collections.abc import AsyncGenerator, Callable, Generatorimport aiosqlite@@ -179,24 +178,6 @@ class HistoryTable(table.Table):if row := await cursor.fetchone():return row[0]- async def get_failed_items(self) -> AsyncGenerator[list[Row]]:- """Returns a list of failed items."""- query = "SELECT referer, download_path,completed_at,created_at FROM media WHERE completed = 0"- cursor = await self.db_conn.execute(query)- while rows := await cursor.fetchmany(_FETCH_MANY_SIZE):- yield cast("list[Row]", rows)-- async def get_all_items(self, after: datetime.date, before: datetime.date) -> AsyncGenerator[list[Row]]:- """Returns a list of all items."""- query = """- SELECT referer,download_path,completed_at,created_at- FROM media WHERE COALESCE(completed_at, '1970-01-01') BETWEEN ? AND ?- ORDER BY completed_at DESC;- """- cursor = await self.db_conn.execute(query, (after.isoformat(), before.isoformat()))- while rows := await cursor.fetchmany(_FETCH_MANY_SIZE):- yield cast("list[Row]", rows)-async def get_unique_download_paths(self) -> AsyncGenerator[list[Row]]:"""Returns a list of unique download paths."""query = "SELECT DISTINCT download_path FROM media"@@ -204,37 +185,6 @@ class HistoryTable(table.Table):while rows := await cursor.fetchmany(_FETCH_MANY_SIZE):yield cast("list[Row]", rows)- async def get_all_bunkr_failed(self) -> AsyncGenerator[list[Row]]:- async for rows in self.get_all_bunkr_failed_via_hash():- yield rows- async for rows in self.get_all_bunkr_failed_via_size():- yield rows-- async def get_all_bunkr_failed_via_size(self) -> AsyncGenerator[list[Row]]:- query = "SELECT referer,download_path,completed_at,created_at from media WHERE file_size=322509;"- try:- cursor = await self.db_conn.execute(query)- while rows := await cursor.fetchmany(_FETCH_MANY_SIZE):- yield cast("list[Row]", rows)-- except Exception:- logger.exception("Error getting bunkr failed via size")-- async def get_all_bunkr_failed_via_hash(self) -> AsyncGenerator[list[Row]]:- query = """- SELECT m.referer,download_path,completed_at,created_at- FROM hash h INNER JOIN media m ON h.download_filename= m.download_filename- WHERE h.hash = 'eb669b6362e031fa2b0f1215480c4e30';- """-- try:- cursor = await self.db_conn.execute(query)- while rows := await cursor.fetchmany(_FETCH_MANY_SIZE):- yield cast("list[Row]", rows)-- except Exception:- logger.exception("Error getting bunkr failed via hash")-async def apply_fixes(db_conn: aiosqlite.Connection) -> None:await _fix_domains(db_conn)diff --git a/cyberdrop_dl/downloader/http.py b/cyberdrop_dl/downloader/http.pyindex dceb1ab33..acd95c7ca 100644--- a/cyberdrop_dl/downloader/http.py+++ b/cyberdrop_dl/downloader/http.py@@ -81,10 +81,7 @@ class Downloader:def __post_init__(self) -> None:self.slots = self._slots- if self.config.settings.download_options.disable_download_attempt_limit:- self.max_attempts = 1- else:- self.max_attempts = self.config.global_settings.rate_limiting_options.download_attempts+ self.max_attempts = self.config.global_settings.rate_limiting_options.download_attempts@propertydef waiting_items(self) -> int:diff --git a/cyberdrop_dl/hasher.py b/cyberdrop_dl/hasher.pyindex 4d3a0e7a8..544e0a594 100644--- a/cyberdrop_dl/hasher.py+++ b/cyberdrop_dl/hasher.py@@ -142,17 +142,16 @@ class Hasher:except IsADirectoryError:return None+ def compute_hash(algo: Literal["xxh128", "md5", "sha256"]) -> asyncio.Task[str | None]:+ return tg.create_task(self._update_db_and_retrive_hash(file, original_filename, referer, algo))+async with self._sem:with self._tui.new_file(file):async with asyncio.TaskGroup() as tg:logger.info("Computing hashes of '%s'", file)- xxxhash = tg.create_task(- self._update_db_and_retrive_hash(file, original_filename, referer, "xxh128")- )- if self.config.add_md5_hash:- tg.create_task(self._update_db_and_retrive_hash(file, original_filename, referer, "md5"))- if self.config.add_sha256_hash:- tg.create_task(self._update_db_and_retrive_hash(file, original_filename, referer, "sha256"))+ xxxhash = compute_hash("xxh128")+ for algo in self.config.extra_hashes:+ _ = compute_hash(algo)return xxxhash.result()diff --git a/cyberdrop_dl/manager.py b/cyberdrop_dl/manager.pyindex ec7bab17e..827e28941 100644--- a/cyberdrop_dl/manager.py+++ b/cyberdrop_dl/manager.py@@ -1,6 +1,5 @@from __future__ import annotations-import asyncioimport contextlibimport dataclassesimport logging@@ -13,7 +12,7 @@ from typing import TYPE_CHECKING, Any, Self, finalfrom pydantic.types import ByteSize-from cyberdrop_dl import __version__, cookies, env, ffmpeg, stats, yaml+from cyberdrop_dl import __version__, aio, env, ffmpeg, stats, yamlfrom cyberdrop_dl.clients.downloads import DownloadClientfrom cyberdrop_dl.clients.http import HTTPClientfrom cyberdrop_dl.config import Config@@ -168,15 +167,17 @@ class Manager:)async def get_cookie_files(self) -> list[Path]:- if self.config.settings.browser_cookies.auto_import:- assert self.config.settings.browser_cookies.browser- cookie_jar = await cookies.extract(self.config.settings.browser_cookies.browser)- await cookies.export(- cookies.filter(cookie_jar, self.config.settings.browser_cookies.sites),- output_path=self.appdata.cookies,- )-- return await asyncio.to_thread(lambda: sorted(self.appdata.cookies.glob("*.txt")))+ path = self.config.settings.cookies.cookies+ if not path:+ return []++ if await aio.is_file(path):+ return [path]++ if await aio.is_dir(path):+ return [f async for f in aio.glob(path, "*.txt")]++ return []@contextlib.contextmanagerdiff --git a/cyberdrop_dl/program_ui.py b/cyberdrop_dl/program_ui.pyindex 80249b0f0..4c38e7a82 100644--- a/cyberdrop_dl/program_ui.py+++ b/cyberdrop_dl/program_ui.py@@ -44,7 +44,6 @@ def changelog() -> str:def run(manager: Manager) -> None:choices: dict[str, Callable[[Manager], bool | None]] = {"Download": lambda _: True,- "Retry failed downloads": _retry_failed_download,"Create file hashes": _scan_and_create_hashes,"Sort files in download folder": _sort_files,"Edit URLs.txt": _edit_urls,@@ -60,11 +59,6 @@ def run(manager: Manager) -> None:break-def _retry_failed_download(manager: Manager) -> bool:- manager.cli_args.retry_failed = True- return True--def _scan_and_create_hashes(manager: Manager) -> None:path = _ask_dir("Select the directory to scan",diff --git a/cyberdrop_dl/progress/dedupe.py b/cyberdrop_dl/progress/dedupe.pyindex 05bf1c164..36ee74f37 100644--- a/cyberdrop_dl/progress/dedupe.py+++ b/cyberdrop_dl/progress/dedupe.py@@ -69,7 +69,7 @@ class DedupeUI(LiveUI):def _init_tasks(self) -> Generator[tuple[str, TaskID]]:yield "deleted", self._progress.add_task("[yellow]Deleted", total=None)- def new_file(self, file: Path):+ def new_file(self, file: Path) -> ProgressHook:task_id = self._files.add_task("[blue]" + escape(str(file.relative_to(self._base_dir))),total=None,diff --git a/cyberdrop_dl/progress/hashing.py b/cyberdrop_dl/progress/hashing.pyindex 0091ee269..8d10f0e4e 100644--- a/cyberdrop_dl/progress/hashing.py+++ b/cyberdrop_dl/progress/hashing.py@@ -32,7 +32,7 @@ class HashingStats:@propertydef computed_hashes(self) -> int:- return sum((self.xxh128, self.md5, self.sha256))+ return self.xxh128 + self.md5 + self.sha256@final@@ -84,12 +84,8 @@ class HashingUI(LiveUI):self._panel.subtitle = f"Files: [white]{current_total:,}[/white], New Computed Hashes: [white]{self._stats.computed_hashes:,}[/white]"return self._panel- def new_file(self, file: Path):- task_id = self._files.add_task(- "[blue]" + escape(str(file.relative_to(self._base_dir))),- total=None,- )-+ def new_file(self, file: Path) -> ProgressHook:+ task_id = self._files.add_task("[blue]" + escape(str(file.relative_to(self._base_dir))), total=None)return ProgressHook(lambda _: None, lambda: 0, lambda: self._files.remove_task(task_id))def add_completed(self, hash_type: Literal["xxh128", "md5", "sha256"]) -> None:diff --git a/cyberdrop_dl/scrape_mapper.py b/cyberdrop_dl/scrape_mapper.pyindex d4356ca53..49ca2fedc 100644--- a/cyberdrop_dl/scrape_mapper.py+++ b/cyberdrop_dl/scrape_mapper.py@@ -3,7 +3,6 @@ from __future__ import annotationsimport asyncioimport contextlibimport dataclasses-import datetimeimport loggingimport reimport time@@ -27,7 +26,7 @@ from cyberdrop_dl.exceptions import JDownloaderError, NoExtensionErrorfrom cyberdrop_dl.logs import log_spacerfrom cyberdrop_dl.progress.scraping import ScrapingUIfrom cyberdrop_dl.url_objects import AbsoluteHttpURL, ScrapeItem-from cyberdrop_dl.utils import dates, filepath, remove_trailing_slash+from cyberdrop_dl.utils import filepath, remove_trailing_slashif TYPE_CHECKING:from collections.abc import AsyncGenerator, Coroutine, Generator, Iterable, Iterator, Sequence@@ -45,18 +44,6 @@ logger = logging.getLogger(__name__)REGEX_LINKS = re.compile(r"(?:http.*?)(?=($|\n|\r\n|\r|\s|\"|\[/URL]|']\[|]\[|\[/img]))")-def _filter_by_date(scrape_item: ScrapeItem, before: datetime.date | None, after: datetime.date | None) -> bool:- skip = False- item_date = scrape_item.completed_at or scrape_item.created_at- if not item_date:- return False- date = dates.from_timestamp(item_date).date()- if (after and date < after) or (before and date > before):- skip = True-- return skip--def _filter_by_domain(scrape_item: ScrapeItem, domain_list: Sequence[str]) -> bool:return any(domain in scrape_item.url.host for domain in domain_list)@@ -213,10 +200,6 @@ class ScrapeMapper:await self._real_debrid.__async_init__()await self._direct_http.__async_post_init__()- item_limit = 0- if self.manager.cli_args.retry_any and self.manager.cli_args.max_items_retry:- item_limit = self.manager.cli_args.max_items_retry-source_name, source = _source(self.manager)async with contextlib.aclosing(source) as items:stats = ScrapeStats(source_name)@@ -234,8 +217,6 @@ class ScrapeMapper:item.children_limits = self.manager.config.settings.download_options.maximum_number_of_childrenitem.download_folder = self.manager.config.settings.files.download_folderif self._should_scrape(item):- if item_limit and stats.count >= item_limit:- breakstats.update(item)self.create_task(self._send_to_crawler(item))@@ -310,13 +291,6 @@ class ScrapeMapper:logger.info(f"Skipping {scrape_item.url} as it is a blocked domain")return False- before = self.manager.cli_args.completed_before- after = self.manager.cli_args.completed_after-- if _filter_by_date(scrape_item, before, after):- logger.info(f"Skipping {scrape_item.url} as it is outside of the desired date range")- return False-skip_hosts = self.manager.config.settings.ignore_options.skip_hostsif skip_hosts and _filter_by_domain(scrape_item, skip_hosts):logger.info(f"Skipping {scrape_item.url} by skip_hosts config")@@ -358,13 +332,6 @@ class ScrapeMapper:def _source(manager: Manager) -> tuple[str, AsyncGenerator[ScrapeItem]]:cli_args = manager.cli_args-- if cli_args.retry_failed:- return "--retry-failed", load_failed_links(manager)- if cli_args.retry_all:- return "--retry-all", load_all_links(manager)- if cli_args.retry_maintenance:- return "--retry-maintenance", load_all_bunkr_failed_links_via_hash(manager)if cli_args.links:return "--links (CLI args)", _load_cli_links(cli_args.links)@@ -429,12 +396,7 @@ def _regex_links(line: str) -> Generator[AbsoluteHttpURL]:def _create_item_from_row(row: aiosqlite.Row) -> ScrapeItem:referer: str = row["referer"]url = AbsoluteHttpURL(referer, encoded="%" in referer)- item = ScrapeItem(url=url, retry_path=Path(row["download_path"]), part_of_album=True)- if completed_at := row["completed_at"]:- item.completed_at = int(datetime.datetime.fromisoformat(completed_at).timestamp())- if created_at := row["created_at"]:- item.created_at = int(datetime.datetime.fromisoformat(created_at).timestamp())- return item+ return ScrapeItem(url=url, retry_path=Path(row["download_path"]), part_of_album=True)def get_crawlers_mapping(*, include_generics: bool = False) -> dict[str, type[Crawler]]:@@ -541,23 +503,3 @@ def _best_match[T](current_map: dict[str, T], domain: str) -> T | None:else:current_map[domain] = found = current_map[best_match]return found---async def load_failed_links(manager: Manager) -> AsyncGenerator[ScrapeItem]:- async for rows in manager.database.history.get_failed_items():- for row in rows:- yield _create_item_from_row(row)---async def load_all_links(manager: Manager) -> AsyncGenerator[ScrapeItem]:- after = manager.cli_args.completed_after or dates.MIN.date()- before = manager.cli_args.completed_before or dates.now_utc().date()- async for rows in manager.database.history.get_all_items(after, before):- for row in rows:- yield _create_item_from_row(row)---async def load_all_bunkr_failed_links_via_hash(manager: Manager) -> AsyncGenerator[ScrapeItem]:- async for rows in manager.database.history.get_all_bunkr_failed():- for row in rows:- yield _create_item_from_row(row)diff --git a/cyberdrop_dl/url_objects.py b/cyberdrop_dl/url_objects.pyindex 7b0cd4e50..d88a70370 100644--- a/cyberdrop_dl/url_objects.py+++ b/cyberdrop_dl/url_objects.py@@ -229,8 +229,6 @@ class ScrapeItem:parent_threads: set[AbsoluteHttpURL] = dataclasses.field(default_factory=set, init=False)type: ScrapeItemType | None = dataclasses.field(default=None, init=False)- completed_at: int | None = dataclasses.field(default=None, init=False)- created_at: int | None = dataclasses.field(default=None, init=False)children_limits: list[int] = dataclasses.field(default_factory=list, init=False)password: str | None = dataclasses.field(default=None, init=False)diff --git a/docs/reference/cli-arguments.md b/docs/reference/cli-arguments.mdindex 23eff56d7..a896dfc78 100644--- a/docs/reference/cli-arguments.md+++ b/docs/reference/cli-arguments.md@@ -38,30 +38,6 @@ For items not explained below, you can find their counterparts in the configuratFolder where Cyberdrop-DL will store it's database, cache and config files.-### `completed-after`--| Type | Default |-| ------ | ------- |-| `date` | `None` |--Only retry downloads that were completed on or after this date. The date should be in ISO 8601 format, for example, `2021-12-23`--{% hint style="info" %}-This option has no effect unless you run CDL with `--retry-all`-{% endhint %}--### `completed-before`--| Type | Default |-| ------ | ------- |-| `date` | `None` |--Only retry downloads that were completed on or before this date. The date should be in ISO 8601 format, for example, `2021-12-23`--{% hint style="info" %}-This option has no effect unless you run CDL with `--retry-all`-{% endhint %}-### `config-file`| Type | Default |@@ -126,18 +102,6 @@ Impersonation allows CDL to make requests and appear to be a legitimate web browThe current default target is `chrome`. The default target can change on any new release without notice{% endhint %}-### `max-items-retry`--| Type | Default |-| ---------------- | ------- |-| `NonNegativeInt` | `0` |--Max number of links to retry. Using `0` means no limit--{% hint style="info" %}-This option has no effect unless you run CDL with one of the retry options: `--retry-all`, `--retry-failed` or `--retry-maintenance`-{% endhint %}-### `portrait`| Type | Default | Action |@@ -154,38 +118,6 @@ Force CDL to run with a vertical layoutShow stats report at the end of a run-### `retry-all`--| Type | Default | Action |-| ---------- | ------- | ------------ |-| `BoolFlag` | `False` | `store_true` |--Retry all downloads--### `retry-failed`--| Type | Default | Action |-| ---------- | ------- | ------------ |-| `BoolFlag` | `False` | `store_true` |--Retry failed downloads--### `retry-maintenance`--| Type | Default | Action |-| ---------- | ------- | ------------ |-| `BoolFlag` | `False` | `store_true` |--Retry download of maintenance files (bunkr). Requires files to be hashed--### `show-supported-sites`--| Type | Default | Action |-| ---------- | ------- | ------------ |-| `BoolFlag` | `False` | `store_true` |--Shows a list of all supported sites and exits-### `ui`| Type | Default |@@ -208,6 +140,7 @@ Values are case insensitive, ex: both `disabled` and `DISABLED` are validBool arguments like options within `Download Options`, `Ignore Options`, `Runtime Options`, etc. can be prefixed with `--no-` to negate them. Ex: `--no-auto-dedupe` will disable auto dedupe, overriding whatever the config option was set to.<!-- START_CLI_OVERVIEW -->+```shellUsage: cyberdrop-dl COMMAND [OPTIONS] [ARGS]@@ -423,4 +356,5 @@ Bulk asynchronous downloader for multiple file hosts│ --refresh-rate [default: 10.0] │╰──────────────────────────────────────────────────────────────────────────────────────────────────╯```+<!-- END_CLI_OVERVIEW -->diff --git a/docs/reference/configuration-options/authentication.md b/docs/reference/configuration-options/authentication.mdindex faa247cb2..6947c7483 100644--- a/docs/reference/configuration-options/authentication.md+++ b/docs/reference/configuration-options/authentication.md@@ -13,26 +13,6 @@ All the options in these list are optional. The default value for all of them is<details>-<summary>Coomer</summary>--- `session`--Value of the `session` cookie from the website. This will allow CDL to download from your favoruites by using `https://coomer.st/favorites` as an input URL.--</details>--<details>--<summary>Kemono</summary>--- `session`--Value of the `session` cookie from the website. This will allow CDL to download from your favoruites by using `https://kemono.cr/favorites` as an input URL.--</details>--<details>-<summary>Forums</summary>{% hint style="warning" %}diff --git a/docs/reference/configuration-options/settings/browser_cookies.md b/docs/reference/configuration-options/settings/browser_cookies.mdindex 78bd87261..0745966c7 100644--- a/docs/reference/configuration-options/settings/browser_cookies.md+++ b/docs/reference/configuration-options/settings/browser_cookies.md@@ -1,56 +1,21 @@# Browser Cookies-Cyberdrop-DL can extract cookies from your browser. These can be used for websites that require login or to pass DDoS-Guard challenges. Only cookies from supported websites are extracted+These can be used for websites that require login or to pass DDoS-Guard challenges.{% hint style="warning" %}The `user-agent` config value **MUST** match the `user-agent` of the browser from which you imported the cookies. If they do not match, the cookies will not work{% endhint %}-## `auto_import`+## `cookies`-| Type | Default |-| ------ | ------- |-| `bool` | `false` |+| Type | Default |+| ---------------- | ------- |+| `Path` or `None` | `None` |-Toggles automatic import of cookies at the start of each run+Path to a file/folder with Netscape cookies with a `.txt` extension. If the path is a folder, all `.txt` in the folder are read (Non recursive)-## `browser`--| Type | Default |-| --------- | --------- |-| `BROWSER` | `firefox` |--A browser to use for extraction. Browser must be a supported browser's name.--### Supported Browsers--| Browser | Windows | Linux | MacOS |-| --------- | ------------------ | ------------------ | ------------------ |-| Arc | :x: | :x: | :white_check_mark: |-| Brave | :x: | :white_check_mark: | :white_check_mark: |-| Chrome | :x: | :white_check_mark: | :white_check_mark: |-| Chromium | :x: | :white_check_mark: | :white_check_mark: |-| Edge | :x: | :white_check_mark: | :white_check_mark: |-| Firefox | :white_check_mark: | :white_check_mark: | :white_check_mark: |-| LibreWolf | :white_check_mark: | :white_check_mark: | :white_check_mark: |-| Lynx | :x: | :white_check_mark: | :x: |-| Opera | :x: | :white_check_mark: | :white_check_mark: |-| Opera_GX | :x: | :x: | :white_check_mark: |-| Safari | :x: | :x: | :white_check_mark: |-| Vivaldi | :x: | :white_check_mark: | :white_check_mark: |-| W3M | :x: | :white_check_mark: | :x: |--## `sites`--| Type | Default |-| --------------- | --------------------------- |-| `list[DOMAINS]` | `[<<ALL_SUPPORTED_SITES>>]` |--List of domains to extract cookies from. You can put any domain on the list, even if they are not officially supported.--## Manual Cookie Extraction--If cookie extraction fails, you can manually extract the cookies from your browser using tools like [cookie-editor](https://cookie-editor.com) and save them at `AppData/Cookies/<site_name>.txt`. The file must be a Netscape formatted cookie file. You can use any name for the file as long as it has a `.txt` extension.+You can extract the cookies from your browser using tools like [cookie-editor](https://cookie-editor.com) and save them as a `.txt` file.+The file must be a Netscape formatted cookie file. You can use any name for the file as long as it has a `.txt` extension.See: [How to extract cookies (DDoSGuard or login errors) #839](https://github.com/Cyberdrop-DL/cyberdrop-dl/discussions/839) for detailed instructionsdiff --git a/docs/reference/configuration-options/settings/download_options.md b/docs/reference/configuration-options/settings/download_options.mdindex 815828f47..b2a126376 100644--- a/docs/reference/configuration-options/settings/download_options.md+++ b/docs/reference/configuration-options/settings/download_options.md@@ -14,16 +14,6 @@ will be changed to:> `Downloads/folderA/image.jpg`-## `disable_download_attempts`--| Type | Default |-| ------ | ------- |-| `bool` | `false` |--By default the program will retry a download twice. You can set this to `true` to disable it and always retry until the download completes.--However, to make sure the program will not run endlessly, there are certain situations where a file will never be retried, like if the program receives a `404` HTTP status, meaning the link is dead.-## `disable_file_timestamps`| Type | Default |@@ -114,38 +104,6 @@ No **FORUM** limit, no **FORUM_POST** limit, no **FILE_HOST_PROFILE** limit, maxSetting this to `true` will remove the "(DOMAIN)" portion of folder names on new downloads.-## `remove_generated_id_from_filenames`--| Type | Default |-| ------ | ------- |-| `bool` | `false` |--Setting this to `true` will remove the alphanumeric ID added to the end of filenames by some websites.--This option only works for URLs from `cyberdrop.me` at the moment.--Multipart archive filenames will be corrected to follow the proper naming pattern for their format.--Supported formats: `.rar` `.7z` `.tar` `.gz` `.bz2` `.zip`--## `scrape_single_forum_post`--| Type | Default |-| ------ | ------- |-| `bool` | `false` |--Setting this to `true` will prevent Cyberdrop-DL from scraping an entire thread if the input URL had an specific post in it.--CDL will only download files within that post.--For most forum sites, the post id is part of the fragment in the URL.--ex: `/thread/iphone-16-16e-16-plus-16-pro-16-promax.256047/page-64#post-7512404` has a post id of `7512404`--If `scrape_single_forum_post` is `false`, CDL will download all post in the thread, from post `7512404` until the last post--If `scrape_single_forum_post` is `true`, CDL will only download files within post `7512404` itself and stop.-## `separate_posts`| Type | Default |@@ -201,15 +159,15 @@ Setting it to `{default}` will use the default format, which is different for ea| `Reddit` | `{title}` || `WordPress` | `{date:%Y-%m-%d} - {id} - {title}` || `eFukt` | `{date:%Y-%m-%d} {title}` |-| `Tiktok` | `{date:%Y-%m-%d} - {id}` |+| `Tiktok` | `{date:%Y-%m-%d} - {id}` |A date without a `format_spec` defaults to ISO 8601 formatYou can use any valid format string supported by python, with the following restrictions:- You can not have positional arguments in the format string. ex: `post {0} from date {1}`-- You can not have unnamed fields in the format string. ex: `post {} from date {}`-- You can not perform operations within the format string. ex: `post {id + 1} from date {date}`+- You can not have unnamed fields in the format string. ex: `post {} from date {}`+- You can not perform operations within the format string. ex: `post {id + 1} from date {date}`- All the fields named in the format string must be valid fields for that format option. CDL will validate this at startup## `skip_download_mark_completed`@@ -273,7 +231,7 @@ Restricts the max number of nested folders CDL will create when `maximum_thread_Values:-- `None`: Create as many nested folders as required (AKA, the same number as `maximum_thread_depth` allows)+- `None`: Create as many nested folders as required (AKA, the same number as `maximum_thread_depth` allows)- `0`: Do not create subfolders, use a flat structure for any nested thread.- `1+`: Create a max of `n` foldersdiff --git a/docs/reference/configuration-options/settings/dupe_cleanup_options.md b/docs/reference/configuration-options/settings/dupe_cleanup_options.mdindex 51f4b75b5..17ad90231 100644--- a/docs/reference/configuration-options/settings/dupe_cleanup_options.md+++ b/docs/reference/configuration-options/settings/dupe_cleanup_options.md@@ -1,6 +1,7 @@---description: These are options for enable/disable hashing and auto dupe deletion---+# Dupe Cleanup OptionsCyberdrop-DL maintains an internal database of all downloaded files, indexed by their hashes. This can be used to automatically delete newly downloaded files if they were downloaded before. To enable auto dupe cleanup:@@ -8,26 +9,6 @@ Cyberdrop-DL maintains an internal database of all downloaded files, indexed by1. Set `hashing` to `IN_PLACE` or `POST_DOWNLOAD`2. Set `auto_dedupe` to `true`-## `add_md5_hash`--| Type | Default |-| ------ | ------- |-| `bool` | `false` |--If enabled, calculates the `md5` hash for every downloaded file and store it in the internal database. This allows the program to match files with sites that provide hash information before downloading them, skipping the download altogether if a match is found--{% hint style="info" %}-`md5` was the default hashing algorithm of Cyberdrop-DL V5. Since v6, the default algorithm is `xxhash128`.-{% endhint %}--## `add_sha256_hash`--| Type | Default |-| ------ | ------- |-| `bool` | `false` |--If enabled, calculates the `sha256` hash for every downloaded file and store it in the internal database. This allows the program to match files with sites that provide hash information before downloading them, skipping the download altogether if a match is found-## `auto_dedupe`| Type | Default |diff --git a/docs/reference/configuration-options/settings/files.md b/docs/reference/configuration-options/settings/files.mdindex daaaa0964..29efe9ec1 100644--- a/docs/reference/configuration-options/settings/files.md+++ b/docs/reference/configuration-options/settings/files.md@@ -52,18 +52,6 @@ The path to the text file containing the URLs you want to download. Each line shYou can also use `html` code. Cyberdrop-DL will parse all the links on the HTML-## `save_pages_html`--| Type | Default |-| ------ | ------- |-| `bool` | `False` |--CDL will save to disk a copy of every requests as an html file. The files will be saved to a folder named `cdl_responses`, located in the same folder as the main log file.--{% hint style="info" %}-Not every request made by CDL returns an HTML page (ex: API requests generally return JSON data). Only HTML responses will be saved-{% endhint %}-## `dump_responses`| Type | Default |diff --git a/docs/reference/configuration-options/settings/logs.md b/docs/reference/configuration-options/settings/logs.mdindex cdc5073cb..5194ebea6 100644--- a/docs/reference/configuration-options/settings/logs.md+++ b/docs/reference/configuration-options/settings/logs.md@@ -10,16 +10,6 @@ Path of the download error log. For relative paths, the final path will be `log_Cyberdrop-DL will output the links it fails to download, the reason and their origin in CSV format.-## `last_forum_post`--| Type | Default | Restrictions |-| ------ | ------------------------------ | --------------------------------------------- |-| `Path` | `Last_Scraped_Forum_Posts.csv` | extension will always be overridden to `.csv` |--Path of the forum-post log file. For relative paths, the final path will be `log_folder` / `last_forum_post`--Cyberdrop-DL will store the link to the last forum posts it scraped from a given forum thread in this file.-## `log_folder`| Type | Default |diff --git a/docs/reference/configuration-options/settings/runtime_options.md b/docs/reference/configuration-options/settings/runtime_options.mdindex 96e25b3d1..1d5a0e1bb 100644--- a/docs/reference/configuration-options/settings/runtime_options.md+++ b/docs/reference/configuration-options/settings/runtime_options.md@@ -146,11 +146,3 @@ This setting specifies speed and it's interpreted as `<value> / second`. ex: `8M{% endhint %}Downloads with a speed lower than this value for more than 10 seconds will be skipped. Set to `0` to disable--## `update_last_forum_post`--| Type | Default |-| ------ | ------- |-| `bool` | `false` |--Updates `input_file` content, adding the last scraped post id to every forum thread URLdiff --git a/docs/simpcity-support-dropped.md b/docs/simpcity-support-dropped.mdindex f5e7bc469..c036579ba 100644--- a/docs/simpcity-support-dropped.md+++ b/docs/simpcity-support-dropped.md@@ -11,39 +11,31 @@ icon: building-circle-xmarkSupport for scraping SimpCity has been removed temporarily. This may be disappointing to some users, but the explanation provided should clarify the reasoning behind this decision. Following the recent DDOS attacks, SimpCity has implemented the following security measures to protect their website:-* SimpCity has implemented a DDOS-Guard browser check.-* Access is now restricted to [whitelisted email domains](https://simpcity.su/threads/emails-august-2024.365869/).-* [New rate limits](https://simpcity.su/threads/rate-limit-429-error.397746/) have been introduced to protect the site.+- SimpCity has implemented a DDOS-Guard browser check.+- Access is now restricted to [whitelisted email domains](https://simpcity.su/threads/emails-august-2024.365869/).+- [New rate limits](https://simpcity.su/threads/rate-limit-429-error.397746/) have been introduced to protect the site.## Why Scraping SimpCity Has Been DisabledCyberdrop-DL allows users to scrape a model’s entire thread quickly, downloading large amounts of content. While convenient, this has created several issues:-* Large-scale scraping can result in downloading content you may never view.-* Such scraping puts additional load on their servers, particularly during DDOS attacks.-* Scraping provides no direct benefit to SimpCity, and in light of these attacks, they have chosen not to support automated scraping.+- Large-scale scraping can result in downloading content you may never view.+- Such scraping puts additional load on their servers, particularly during DDOS attacks.+- Scraping provides no direct benefit to SimpCity, and in light of these attacks, they have chosen not to support automated scraping.For these reasons, SimpCity has removed the Cyberdrop-DL thread, and scraping for their site has been disabled in order to reduce the strain on their servers.-## How to Reduce the Impact of Cyberdrop-DL Usage--To help reduce the load on other websites, the `update_last_forum_post` setting has been enabled by default in all users' configs. This setting speeds up scrapes by picking up where the last session left off, rather than re-scraping entire threads.--You can disable this setting if you prefer, but it is strongly discouraged.--In addition, the default rate-limiting settings have been adjusted to further reduce the impact on websites.-## Usage Best PracticesI encourage you to use the program responsibly. Here are some tips to help minimize the impact on websites:-* Avoid running multiple scraping sessions repeatedly in a short span of time.-* Regularly clean up your URLs file by removing links you no longer need, and reducing how often you run the program.-* Be selective with what you download. It’s helpful to quickly scan content to avoid downloading files you'll delete later.+- Avoid running multiple scraping sessions repeatedly in a short span of time.+- Regularly clean up your URLs file by removing links you no longer need, and reducing how often you run the program.+- Be selective with what you download. It’s helpful to quickly scan content to avoid downloading files you'll delete later.## Alternatives to Scraping SimpCityIf you wish to continue downloading from SimpCity, you can use Tampermonkey scripts like these ones:-* [SimpCity Tampermonkey Forum Downloader](https://simpcity.su/threads/forum-post-downloader-tampermonkey-script.96714/).-* [Forums Link Grabber](https://github.com/Garcarius/forumslinkgraber)+- [SimpCity Tampermonkey Forum Downloader](https://simpcity.su/threads/forum-post-downloader-tampermonkey-script.96714/).+- [Forums Link Grabber](https://github.com/Garcarius/forumslinkgraber)diff --git a/tests/crawlers/test_xenforo.py b/tests/crawlers/test_xenforo.pyindex a1435972a..29e1e2022 100644--- a/tests/crawlers/test_xenforo.py+++ b/tests/crawlers/test_xenforo.py@@ -665,69 +665,6 @@ def test_is_attachment_empty_string_should_be_false() -> None:assert TEST_CRAWLER.is_attachment("") is False-class TestCheckPostId:- @pytest.mark.parametrize(- (- "init_post_id",- "current_post_id",- "scrape_single_forum_post",- "expected_continue_scraping",- "expected_scrape_this_post",- ),- [- # init_post_id > current_post_id- (100, 90, True, True, False),- (100, 90, False, True, False),- # case init_post_id == current_post_id- (100, 100, True, False, True),- (100, 100, False, True, True),- # case init_post_id < current_post_id- (100, 110, True, False, False),- (100, 110, False, True, True),- ],- )- def test_init_post_id_was_provided(- self,- init_post_id: int,- current_post_id: int,- *,- scrape_single_forum_post: bool,- expected_continue_scraping: bool,- expected_scrape_this_post: bool,- ) -> None:- continue_scraping, scrape_this_post = _forum.check_post_id(- init_post_id,- current_post_id,- scrape_single_forum_post=scrape_single_forum_post,- )- assert continue_scraping == expected_continue_scraping- assert scrape_this_post == expected_scrape_this_post-- def test_no_init_post_id_and_scrape_single_post_false(self) -> None:- init_post_id = None- current_post_id = 100- scrape_single_forum_post = False- continue_scraping, scrape_this_post = _forum.check_post_id(- init_post_id,- current_post_id,- scrape_single_forum_post=scrape_single_forum_post,- )- assert continue_scraping is True- assert scrape_this_post is True-- def test_no_init_post_id_and_scrape_single_post_true_raises_error(self) -> None:- init_post_id = None- current_post_id = 100- scrape_single_forum_post = True-- with pytest.raises(AssertionError):- _forum.check_post_id(- init_post_id,- current_post_id,- scrape_single_forum_post=scrape_single_forum_post,- )--# original post_id = 23549340POST_TEMPLATE = """<article class="message message--post js-post js-inlineModContainer" data-author="" data-content="post-{id}" id="js-post-{id}" itemscope="" itemtype="https://schema.org/Comment" itemid="https://simpcity.su/posts/{id}/">diff --git a/tests/test_database.py b/tests/test_database.pyindex 0047c0913..5a0293ad1 100644--- a/tests/test_database.py+++ b/tests/test_database.py@@ -1,6 +1,5 @@from __future__ import annotations-import datetimefrom pathlib import Pathfrom typing import TYPE_CHECKING, cast@@ -11,7 +10,7 @@ from cyberdrop_dl.database import Database, schemafrom cyberdrop_dl.exceptions import DatabaseErrorfrom cyberdrop_dl.scrape_mapper import _create_item_from_rowfrom cyberdrop_dl.url_objects import AbsoluteHttpURL, ScrapeItem-from cyberdrop_dl.utils import dates, parse_url+from cyberdrop_dl.utils import parse_urlif TYPE_CHECKING:import aiosqlite@@ -35,51 +34,12 @@ def row() -> aiosqlite.Row:return cast("aiosqlite.Row", _MOCK_ROW.copy()) # pyright: ignore[reportInvalidCast]-def row_with_dates(row) -> aiosqlite.Row:- row["completed_at"] = dates.now_utc().isoformat()- row["created_at"] = datetime.datetime(2023, 1, 1, 10, 0, 0, 0, tzinfo=datetime.UTC).isoformat()- return row--def test_scrape_item_creation(row: aiosqlite.Row) -> None:item = _create_item_from_row(row)assert isinstance(item, ScrapeItem)assert item.url == AbsoluteHttpURL("https://drive.google.com/file/d/1F0YBsnQRvrMbK0p9UlnyLu88kqQ0j_F6/edit")assert item.retry_path == Path("/cdl/downloads")assert item.part_of_album is True- assert item.completed_at is None- assert item.created_at is None---def test_item_with_completed_at(row_with_dates) -> None:- completed_at_str = row_with_dates["completed_at"]- row_with_dates["created_at"] = None-- item = _create_item_from_row(row_with_dates)- expected_timestamp = int(dates.parse_iso(completed_at_str).timestamp())- assert item.completed_at == expected_timestamp- assert item.created_at is None---def test_item_with_created_at(row) -> None:- now = dates.now_utc()- row["created_at"] = now.isoformat()-- item = _create_item_from_row(row)- assert item.created_at == int(now.timestamp())- assert item.completed_at is None---def test_item_with_both_dates(row_with_dates) -> None:- completed_at_str = row_with_dates["completed_at"]- created_at_str = row_with_dates["created_at"]-- item = _create_item_from_row(row_with_dates)- expected_completed_timestamp = int(dates.parse_iso(completed_at_str).timestamp())- expected_created_timestamp = int(dates.parse_iso(created_at_str).timestamp())- assert item.completed_at == expected_completed_timestamp- assert item.created_at == expected_created_timestampdef test_missing_download_path(row) -> None:@@ -89,13 +49,6 @@ def test_missing_download_path(row) -> None:_create_item_from_row(row)-def test_invalid_date_format(row) -> None:- row["completed_at"] = "invalid date"-- with pytest.raises(ValueError):- _create_item_from_row(row)--@pytest.mark.parametrize(("url", "expected"),[diff --git a/tests/test_hashing.py b/tests/test_hashing.pyindex 4f90cefcb..03ea424a9 100644--- a/tests/test_hashing.py+++ b/tests/test_hashing.py@@ -53,8 +53,9 @@ async def test_hash_directory_scanner(manager: Manager, expected_results: set[tun_files = max(count.values())algos = count.keys()assert len(expected_results) == len(algos) * n_files- manager.config.settings.dupe_cleanup_options.add_md5_hash = "md5" in algos- manager.config.settings.dupe_cleanup_options.add_sha256_hash = "sha256" in algos+ options = manager.config.settings.dupe_cleanup_options+ options.hashes = tuple(algos) # pyright: ignore[reportAttributeAccessIssue]+ options.re_compute()manager.config.settings.files.download_folder.mkdir(parents=True)db_path = manager.appdata.db_file@@ -68,8 +69,9 @@ async def test_hash_directory_scanner(manager: Manager, expected_results: set[tuasync def test_hash_directory_does_not_crash_with_subfolders(tmp_cwd: Path, manager: Manager) -> None:- manager.config.settings.dupe_cleanup_options.add_md5_hash = True- manager.config.settings.dupe_cleanup_options.add_sha256_hash = True+ options = manager.config.settings.dupe_cleanup_options+ options.hashes = "md5", "sha256"+ options.re_compute()hash_folder = tmp_cwd / "sorted_downloads"here = Path(__file__).parentfiles = [hash_folder / f.relative_to(here) for f in here.rglob("*") if f.is_file()]