Skip to content

Bulk asynchronous downloader for multiple file hosts

feat: add `retry` command (#1987)

NTFSvolumefb5cb2eecaa0
diff --git a/.gitignore b/.gitignore
index 08845fa32..2e910285a 100644
--- a/.gitignore
+++ b/.gitignore
@@ -3,6 +3,7 @@
/Test-AppData-Dir/
/AppData*/
/Downloads/
+/downloads/
/Old Files/
*.log
*.profiling
diff --git a/.zed/debug.json b/.zed/debug.json
index 469d2ef3f..c586b6ca0 100644
--- a/.zed/debug.json
+++ b/.zed/debug.json
@@ -1,6 +1,6 @@
[
{
- "label": "Run CDL debug mode",
+ "label": "Run CDL - download",
"adapter": "Debugpy",
"request": "launch",
"program": "cyberdrop_dl/__main__.py",
@@ -26,4 +26,30 @@
"CDL_ENABLE_TWITTER": "true",
},
},
+ {
+ "label": "Run CDL - retry failed",
+ "adapter": "Debugpy",
+ "request": "launch",
+ "program": "cyberdrop_dl/__main__.py",
+ "justMyCode": false,
+ "purpose": ["debug-test"],
+ "args": [
+ "retry",
+ "failed",
+ "--ignore-history",
+ "--dump-json",
+ "--min-free-space",
+ "512MB",
+ "--downloads",
+ "2",
+ "--flaresolverr",
+ "http://localhost:8191",
+ "--log-file",
+ "debug_run.log",
+ ],
+ "env": {
+ "PYTHONASYNCIODEBUG": "1",
+ "CDL_ENABLE_TWITTER": "true",
+ },
+ },
]
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b0961b489..122fca1c0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -36,7 +36,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- New `--hashes` option to control which hashes CDL computes for new downloads
- New `--database-file` option
- New `--cache-file` option
-- New `download` CLI command (replaces the `--download` argument)
+- New `download` CLI command (replaces `--download` argument)
+- New `retry` CLI command (replaces `--retry-failed` and `--retry-all` arguments)
- New `config` CLI command
- New `cache` CLI command
- New `hash` CLI command
@@ -45,19 +46,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Changed
- The config file format has changed. All configs (`Auth`, `Global` and `Setttings`) are now a single file. Several options have new names, new defaults and new groups
-- A default config file will noo longer be created. You can manually create a default one from the `Edit config` option on the main menu
+- A default config file will no longer be created. You can manually create a default one from the `Edit config` option on the main menu or running `cyberdrop-dl config new`
- Validate config in strict mode. If a config has an unknown entry, CDL will refuse to run instead of ignoring it
- Apprise URLs are now part of the main config file instead of a dedicated `apprise.txt` file
- Refuse to start if the current database schema is older than `v9.15.0`
- Cookies with not be automatically loaded from `AppData/cookies`. Path to cookies needs to be specified with `--cookies`
-- Always remove generated id from filenames (Cyberdrop)
+- Retry options will no longer use the original path of the first download attempt. Download path will be generated based on current config options (like normal downloads)
- Compute `xxh128`, `md5` and `sha256` hashes by default
- `--deep-scrape` will no longer reset after a single run
- `--input-file` is now a CLI only arg
-- If supplied, `--input-file` needs to be a valid file that exists
+- If supplied, `--input-file` needs to be a valid file that already exists
- Refuse to run if both URLs and `--input-file` are passed as arguments
- Detect and report BasedFlare anti-bot protection
- Limit max queued downloads of a single site to the config concurrency limit x10 (capped at 50). All scraping for a site will be paused if its queue is full
+- Always remove generated id from filenames (Cyberdrop)
The following options, which were CLI only arguments, now have dedicated config entries:
diff --git a/cyberdrop_dl/cli.py b/cyberdrop_dl/cli.py
index bcfb42ced..8dcb4ece9 100644
--- a/cyberdrop_dl/cli.py
+++ b/cyberdrop_dl/cli.py
@@ -13,7 +13,10 @@ from cyberdrop_dl.commands.cleanup import app as cleanup_app
from cyberdrop_dl.commands.config import app as config_app
from cyberdrop_dl.commands.database import app as database_app
from cyberdrop_dl.commands.hash import compute_hashes
+from cyberdrop_dl.commands.retry import app as retry_app
+from cyberdrop_dl.commands.retry import create_retry_source
from cyberdrop_dl.commands.scrape import download, prepare_manager, scrape
+from cyberdrop_dl.scrape_source import RetryScrapeSource, RetrySource
app = App(
name="cyberdrop-dl",
@@ -45,8 +48,14 @@ def main_menu(
with prepare_manager(cli_args, cli_overrides=None)() as manager:
from cyberdrop_dl import program_ui
- program_ui.run(manager, input_file)
- scrape(manager, input_file)
+ source = program_ui.run(manager, input_file)
+ scrape(manager, source=_parse_scrape_source(source))
+
+
+def _parse_scrape_source(src: Path | RetrySource) -> Path | RetryScrapeSource:
+ if isinstance(src, Path):
+ return src
+ return create_retry_source(src)
@app.command
@@ -66,7 +75,7 @@ def report() -> None:
app.console.print(generate_report())
-for cmd in download, database_app, cleanup_app, config_app, cache_app:
+for cmd in download, database_app, cleanup_app, config_app, cache_app, retry_app:
app.command(cmd)
diff --git a/cyberdrop_dl/commands/retry.py b/cyberdrop_dl/commands/retry.py
new file mode 100644
index 000000000..5ee33dd15
--- /dev/null
+++ b/cyberdrop_dl/commands/retry.py
@@ -0,0 +1,59 @@
+import datetime
+import logging
+from typing import Annotated
+
+from cyclopts import App, Parameter
+
+from cyberdrop_dl.commands import CLIarguments
+from cyberdrop_dl.commands.scrape import prepare_manager, scrape
+from cyberdrop_dl.config import Config
+from cyberdrop_dl.exceptions import CDLConfigRuntimeErrorsGroup
+from cyberdrop_dl.models import ConfigModel
+from cyberdrop_dl.scrape_source import RetryScrapeSource, RetrySource
+
+app = App(name="retry", help="Retry downloads from the database")
+logger = logging.getLogger(__name__)
+
+
+@Parameter(name="*")
+class RetryArgs(ConfigModel):
+ from_: Annotated[datetime.date, Parameter(name="from")] = datetime.date(1970, 1, 1)
+ "Only retry URLs added to the database since this date"
+
+ to: Annotated[datetime.date | None, Parameter(show_default=True)] = None
+ "Only retry URLs added to the database before this date"
+
+ force_original_path: bool = False
+ "Ignore current config options and force downloads to use the exact same path of the initial download attempt"
+
+ cli_args: CLIarguments | None = None
+ cli_overrides: Config | None = None
+
+
+def _tomorrow() -> datetime.date:
+ return datetime.datetime.now(tz=datetime.UTC).date() + datetime.timedelta(days=1)
+
+
+def create_retry_source(retry: RetrySource, args: RetryArgs | None = None) -> RetryScrapeSource:
+ args = args or RetryArgs()
+ if args.force_original_path:
+ error = RuntimeError("Support for '--force-original-path' has been temporarily removed")
+ raise CDLConfigRuntimeErrorsGroup("Unsupported option", (error,))
+
+ return RetryScrapeSource(retry, after=args.from_, before=args.to or _tomorrow())
+
+
+def failed(*, args: RetryArgs | None = None) -> None:
+ """Retry failed downloads"""
+ args = args or RetryArgs()
+ with prepare_manager(args.cli_args, args.cli_overrides)() as manager:
+ scrape(manager, source=create_retry_source(RetrySource.FAILED, args))
+
+
[email protected](name="all")
+def retry_all(*, args: RetryArgs | None = None) -> None:
+ "Retry all downloads"
+ args = args or RetryArgs()
+ with prepare_manager(args.cli_args, args.cli_overrides)() as manager:
+ scrape(manager, source=create_retry_source(RetrySource.ALL, args))
diff --git a/cyberdrop_dl/commands/scrape.py b/cyberdrop_dl/commands/scrape.py
index 97fd84c70..3d532fa5c 100644
--- a/cyberdrop_dl/commands/scrape.py
+++ b/cyberdrop_dl/commands/scrape.py
@@ -16,7 +16,7 @@ from cyberdrop_dl.exceptions import CDLConfigRuntimeErrorsGroup
from cyberdrop_dl.logs import log_spacer, set_console_level, setup_file_logging
from cyberdrop_dl.models import merge_models
from cyberdrop_dl.models.types import HttpURL # noqa: TC001
-from cyberdrop_dl.scrape_source import URLSource
+from cyberdrop_dl.scrape_source import URLsSource
from cyberdrop_dl.utils import cleanup
logger = logging.getLogger(__name__)
@@ -25,17 +25,17 @@ if TYPE_CHECKING:
from cyclopts.argument import ArgumentCollection
from cyberdrop_dl.manager import Manager
- from cyberdrop_dl.scrape_source import URLSource
+ from cyberdrop_dl.scrape_source import RetryScrapeSource, URLsSource
-def scrape(manager: Manager, source: URLSource) -> None:
+def scrape(manager: Manager, source: URLsSource | RetryScrapeSource) -> None:
from cyberdrop_dl import aio
with setup_file_logging(manager.config.logs.files.main, level=manager.config.logs.effective_level):
aio.run(_scrape(manager, source))
-async def _scrape(manager: Manager, source: URLSource) -> None:
+async def _scrape(manager: Manager, source: URLsSource | RetryScrapeSource) -> None:
from cyberdrop_dl import ffmpeg
from cyberdrop_dl.scrape_mapper import ScrapeMapper
diff --git a/cyberdrop_dl/program_ui.py b/cyberdrop_dl/program_ui.py
index 1c42e8017..1b0d82be6 100644
--- a/cyberdrop_dl/program_ui.py
+++ b/cyberdrop_dl/program_ui.py
@@ -18,6 +18,7 @@ from cyberdrop_dl.prompts import (
console,
enter_to_continue,
)
+from cyberdrop_dl.scrape_source import RetrySource
from cyberdrop_dl.sorter import Sorter
from cyberdrop_dl.utils import text_editor
@@ -40,10 +41,11 @@ def _changelog() -> str:
return _changelog_content
-def run(manager: Manager, input_file: Path) -> None:
+def run(manager: Manager, input_file: Path) -> RetrySource | Path:
_INPUT_FILE.set(input_file)
- choices: dict[str, Callable[[Manager], bool | None]] = {
- "Download": lambda _: True,
+ choices: dict[str, Callable[[Manager], RetrySource | Path | None]] = {
+ "Download": lambda _: input_file,
+ "Retry failed downloads": lambda _: RetrySource.FAILED,
"Create file hashes": _scan_and_create_hashes,
"Sort files in download folder": _sort_files,
"Edit URLs.txt": lambda _: _edit_urls(),
@@ -55,9 +57,9 @@ def run(manager: Manager, input_file: Path) -> None:
while True:
_app_header(manager)
answer = ask_choices(choices)
- done = choices[answer](manager)
- if done:
- break
+ source = choices[answer](manager)
+ if source:
+ return source
def _scan_and_create_hashes(manager: Manager) -> None:
diff --git a/cyberdrop_dl/scrape_mapper.py b/cyberdrop_dl/scrape_mapper.py
index 696f9b773..4f69101ae 100644
--- a/cyberdrop_dl/scrape_mapper.py
+++ b/cyberdrop_dl/scrape_mapper.py
@@ -5,6 +5,7 @@ import contextlib
import dataclasses
import logging
import time
+from pathlib import Path
from typing import TYPE_CHECKING, Any, Literal, Self
from pydantic.types import ByteSize
@@ -15,13 +16,19 @@ from cyberdrop_dl.crawlers import ALLOW_NO_EXT, create_crawlers
from cyberdrop_dl.exceptions import JDownloaderError, NoExtensionError
from cyberdrop_dl.logs import log_spacer
from cyberdrop_dl.progress.scraping import ScrapingUI
-from cyberdrop_dl.scrape_source import ScrapeSource, URLSource
+from cyberdrop_dl.scrape_source import (
+ RetryQuery,
+ RetryScrapeSource,
+ URLsSource,
+ load_items_from_db,
+ load_items_from_file,
+ load_items_from_iterable,
+)
from cyberdrop_dl.url_objects import AbsoluteHttpURL, ScrapeItem, ScrapeItemType
from cyberdrop_dl.utils import remove_trailing_slash
if TYPE_CHECKING:
- from collections.abc import AsyncGenerator, Coroutine, Generator, Iterator, Sequence
- from pathlib import Path
+ from collections.abc import AsyncGenerator, Coroutine, Generator, Iterable, Iterator, Sequence
from cyberdrop_dl.clients.jdownloader import JDownloader
from cyberdrop_dl.config import Config
@@ -210,25 +217,23 @@ class ScrapeMapper:
await self._direct_http.__async_post_init__()
self._ready = True
- async def run(self, src: URLSource | None = None) -> ScrapeStats:
+ async def _wait_until_scrape_is_done(self, stats: ScrapeStats) -> None:
+ _ = await self._done.wait()
+ self.tui.hide_scrape_panel()
+ stats.url_count.update(
+ (crawler.DOMAIN, count) for crawler in self._factory if (count := len(crawler._scraped_items))
+ )
+
+ async def run(self, src: URLsSource | RetryScrapeSource | None = None) -> ScrapeStats:
await self.__async_init__()
if src is None:
return ScrapeStats("")
- source = ScrapeSource(src)
- stats = ScrapeStats(source.name)
- async with source.items() as items:
-
- async def wait_until_scrape_is_done() -> None:
- _ = await self._done.wait()
- self.tui.hide_scrape_panel()
- stats.url_count.update(
- (crawler.DOMAIN, count) for crawler in self._factory if (count := len(crawler._scraped_items))
- )
-
- self.create_download_task(wait_until_scrape_is_done())
-
+ stats, get_items = _parse_source(src, self.manager)
+ async with contextlib.aclosing(get_items) as items:
+ self.create_download_task(self._wait_until_scrape_is_done(stats))
max_children = _build_max_children_map(self.manager.config)
+
async for item in items:
item.max_children = max_children
item.download_folder = self.manager.config.download_folder
@@ -464,3 +469,26 @@ def _build_max_children_map(config: Config) -> dict[ScrapeItemType, int]:
ScrapeItemType.PROFILE: max_children.profile,
ScrapeItemType.ALBUM: max_children.album,
}
+
+
+def _parse_source(
+ src: RetryScrapeSource | Path | Iterable[AbsoluteHttpURL], manager: Manager
+) -> tuple[ScrapeStats, AsyncGenerator[ScrapeItem]]:
+ match src:
+ case RetryScrapeSource():
+ source = src.source.value
+ query = RetryQuery[src.source.name]
+ items = load_items_from_db(
+ manager.database.conn,
+ query,
+ after=src.after,
+ before=src.before,
+ )
+ case Path():
+ source = src
+ items = load_items_from_file(src)
+ case _:
+ source = "--links (CLI args)"
+ items = load_items_from_iterable(src)
+
+ return ScrapeStats(source), items
diff --git a/cyberdrop_dl/scrape_source.py b/cyberdrop_dl/scrape_source.py
index 58f81b8fb..0c1683322 100644
--- a/cyberdrop_dl/scrape_source.py
+++ b/cyberdrop_dl/scrape_source.py
@@ -1,45 +1,61 @@
from __future__ import annotations
-import contextlib
import dataclasses
import logging
import re
+from enum import StrEnum
from pathlib import Path
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, Any
from cyberdrop_dl import aio
-from cyberdrop_dl.url_objects import AbsoluteHttpURL, ScrapeItem
+from cyberdrop_dl.url_objects import AbsoluteHttpURL, RetryInfo, ScrapeItem
+from cyberdrop_dl.utils.dataclass import deserialize
if TYPE_CHECKING:
- from collections.abc import AsyncGenerator, Generator, Iterable
+ import datetime
+ from collections.abc import AsyncGenerator, Generator, Iterable, Mapping
-
-type URLSource = Path | Iterable[AbsoluteHttpURL]
-REGEX_LINKS = re.compile(r"(?:http.*?)(?=($|\n|\r\n|\r|\s|\"|\[/URL]|']\[|]\[|\[/img]))")
+ import aiosqlite
logger = logging.getLogger(__name__)
+_FETCH_MANY_SIZE = 1000
+_REGEX_LINKS = re.compile(r"(?:http.*?)(?=($|\n|\r\n|\r|\s|\"|\[/URL]|']\[|]\[|\[/img]))")
[email protected](slots=True)
-class ScrapeSource:
- source: URLSource
- name: str = ""
+type URLsSource = Path | Iterable[AbsoluteHttpURL]
+
+
+class RetryQuery(StrEnum):
+ FAILED = """
+ SELECT domain, url_path, referer, download_path, download_filename FROM media
+ WHERE
+ completed = 0 AND created_at BETWEEN ? AND ?
+ ORDER BY
+ created_at DESC;
+ """
+
+ ALL = """
+ SELECT domain, url_path, referer, download_path, download_filename FROM media
+ WHERE
+ created_at BETWEEN ? AND ?
+ ORDER BY
+ created_at DESC;
+ """
- def __post_init__(self) -> None:
- if not self.name:
- self.name = str(self.source) if isinstance(self.source, Path) else "--links (CLI args)"
- def _items(self) -> AsyncGenerator[ScrapeItem]:
- if isinstance(self.source, Path):
- return _load_urls_from_file(self.source)
+class RetrySource(StrEnum):
+ FAILED = "retry failed"
+ ALL = "retry all"
- return _load_cli_links(self.source)
- def items(self) -> contextlib.aclosing[AsyncGenerator[ScrapeItem]]:
- return contextlib.aclosing(self._items())
[email protected](slots=True)
+class RetryScrapeSource:
+ source: RetrySource
+ after: datetime.date
+ before: datetime.date
-async def _load_urls_from_file(file: Path) -> AsyncGenerator[ScrapeItem]:
+async def load_items_from_file(file: Path) -> AsyncGenerator[ScrapeItem]:
async for group_name, urls in _parse_input_file_groups(file):
for url in urls:
item = ScrapeItem.from_url(url)
@@ -70,7 +86,7 @@ async def _parse_input_file_groups(input_file: Path) -> AsyncGenerator[tuple[str
yield ("", list(_regex_links(line)))
-async def _load_cli_links(links: Iterable[AbsoluteHttpURL]) -> AsyncGenerator[ScrapeItem]:
+async def load_items_from_iterable(links: Iterable[AbsoluteHttpURL]) -> AsyncGenerator[ScrapeItem]:
for url in links:
yield ScrapeItem.from_url(url)
@@ -85,10 +101,32 @@ def _regex_links(line: str) -> Generator[AbsoluteHttpURL]:
if line.startswith("#"):
return
- http_urls = (url.group().replace(".md.", ".") for url in re.finditer(REGEX_LINKS, line))
+ http_urls = (url.group().replace(".md.", ".") for url in re.finditer(_REGEX_LINKS, line))
for link in http_urls:
try:
encoded = "%" in link
yield AbsoluteHttpURL(link, encoded=encoded)
except Exception as e: # noqa: BLE001
logger.error(f"Unable to parse URL from input file: {link} {e:!r}")
+
+
+async def load_items_from_db(
+ db_conn: aiosqlite.Connection,
+ query: RetryQuery,
+ *,
+ after: datetime.date,
+ before: datetime.date,
+) -> AsyncGenerator[ScrapeItem]:
+ cursor = await db_conn.execute(query, (after.isoformat(), before.isoformat()))
+ while rows := await cursor.fetchmany(_FETCH_MANY_SIZE):
+ for row in rows:
+ yield _create_item_from_row(dict(row))
+
+
+def _create_item_from_row(row: Mapping[str, Any]) -> ScrapeItem:
+ referer: str = row["referer"]
+ url = AbsoluteHttpURL(referer, encoded="%" in referer)
+ item = ScrapeItem.from_url(url)
+ item.part_of_album = True
+ item.retry_info = deserialize(RetryInfo, dict(row), referer=url, download_path=Path(row["download_path"]))
+ return item
diff --git a/cyberdrop_dl/url_objects.py b/cyberdrop_dl/url_objects.py
index f77dd6709..12bca4ff0 100644
--- a/cyberdrop_dl/url_objects.py
+++ b/cyberdrop_dl/url_objects.py
@@ -188,6 +188,15 @@ class MediaItem:
return me
[email protected](slots=True, frozen=True)
+class RetryInfo:
+ domain: str
+ url_path: str
+ download_path: Path
+ download_filename: str
+ referer: AbsoluteHttpURL
+
+
@final
@dataclasses.dataclass(kw_only=True, slots=True)
class ScrapeItem:
@@ -206,6 +215,7 @@ class ScrapeItem:
_children_limit: int = 0
_type: ScrapeItemType | None = None
_uploaded_at: int | None = None
+ retry_info: RetryInfo | None = None
__repr__ = signature.simple_repr("url", "folders", "uploaded_at")
diff --git a/tests/test_database.py b/tests/test_database.py
index 485ff3098..cdeac31c2 100644
--- a/tests/test_database.py
+++ b/tests/test_database.py
@@ -8,6 +8,7 @@ from cyberdrop_dl import aio, scrape_mapper
from cyberdrop_dl.crawlers.crawler import _prepare_download_path
from cyberdrop_dl.database import Database, common, schema
from cyberdrop_dl.exceptions import DatabaseError
+from cyberdrop_dl.scrape_source import _create_item_from_row
from cyberdrop_dl.url_objects import AbsoluteHttpURL, ScrapeItem
from cyberdrop_dl.utils import parse_url
@@ -151,3 +152,23 @@ async def test_db_schema_dump(tmp_cwd: Path) -> None:
current_schema = await schema.dump(db.conn)
assert current_schema == schema.V9_15_0
+
+
+def test_create_item_from_row() -> None:
+ referer, domain, url_path, download_path, download_filename = (
+ "https://example.com/a/b/c/",
+ "example.com",
+ "/a/b/c",
+ "/home/user/downloads",
+ "movie.mp4",
+ )
+
+ item = _create_item_from_row(locals())
+ assert item.url.human_repr() == referer
+ assert item.part_of_album is True
+ info = item.retry_info
+ assert info
+ assert info.domain == domain
+ assert info.url_path == url_path
+ assert info.download_path == Path(download_path)
+ assert info.download_filename == download_filename