Skip to content

Bulk asynchronous downloader for multiple file hosts

fix: solve proof of work challenge (Fileditch) (#2026)

NTFSvolume979171dd53af
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0dd71dabe..c887f44af 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -24,9 +24,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## UNRELEASED
+### Changed
+
+- Hardcoded a new limit of 1 scrape URL at a time (Fileditch)
+
### Fixed
- Dead lock if more that 50 downloads are queued (Filester)
+- Solve proof of work challenge (Fileditch)
## [10.2.0] - 2026-07-13
diff --git a/cyberdrop_dl/crawlers/fileditch.py b/cyberdrop_dl/crawlers/fileditch.py
index 6d221690a..2b69b77ec 100644
--- a/cyberdrop_dl/crawlers/fileditch.py
+++ b/cyberdrop_dl/crawlers/fileditch.py
@@ -1,16 +1,20 @@
from __future__ import annotations
+import dataclasses
+import hashlib
import json
-from typing import TYPE_CHECKING, ClassVar, override
+from typing import TYPE_CHECKING, ClassVar, Self, override
-from cyberdrop_dl.crawlers.crawler import Crawler, SupportedPaths
+from cyberdrop_dl import multi_process
+from cyberdrop_dl.crawlers.crawler import Crawler, RateLimit, SupportedPaths
from cyberdrop_dl.exceptions import ScrapeError
from cyberdrop_dl.url_objects import AbsoluteHttpURL
from cyberdrop_dl.utils import css, extr_text, parse_url
+from cyberdrop_dl.utils.dataclass import DictDataclass
from cyberdrop_dl.utils.errors import error_handling_wrapper
if TYPE_CHECKING:
- from bs4 import BeautifulSoup
+ import bs4
from cyberdrop_dl.url_objects import ScrapeItem
@@ -29,12 +33,11 @@ class FileditchCrawler(Crawler):
}
PRIMARY_URL: ClassVar[AbsoluteHttpURL] = AbsoluteHttpURL("https://fileditchfiles.me/")
DOMAIN: ClassVar[str] = "fileditch"
+ _RATE_LIMIT: ClassVar[RateLimit] = 3, 1
async def fetch(self, scrape_item: ScrapeItem) -> None:
match scrape_item.url.parts[1:]:
- case [*_, "file.php"]:
- return await self.file(scrape_item)
- case [a, _, *_] if a.startswith(("beta", "temp", "alpha")):
+ case [_, _, *_]:
return await self.file(scrape_item)
case _:
raise ValueError
@@ -43,11 +46,8 @@ class FileditchCrawler(Crawler):
@override
def transform_url(cls, url: AbsoluteHttpURL) -> AbsoluteHttpURL:
url = super().transform_url(url)
- if url.name == "file.php" and (file_id := url.query.get("f")):
- # Their servers accept any number of empty parts before the file
- # Remove them to get a canonical URL
- # https:/fileditchfiles.me////////file.php?f=/b70/1234 -> https:/fileditchfiles.me/file.php?f=/b70/1234
- return (url.origin() / "file.php").with_query(f=file_id)
+ if url.name == "file.php" and (path := url.query.get("f")):
+ return url.with_path(path)
return url
@error_handling_wrapper
@@ -55,7 +55,7 @@ class FileditchCrawler(Crawler):
if await self.check_complete_from_referer(scrape_item.url):
return
- soup = await self.request_soup(scrape_item.url)
+ soup = await self.request_pow_soup(scrape_item.url)
if soup.select_one(".gone-path"):
raise ScrapeError(410)
src = _extract_dl_url(soup)
@@ -65,8 +65,75 @@ class FileditchCrawler(Crawler):
filename, ext = self.get_filename_and_ext(src.name)
await self.handle_file(src, scrape_item, filename, ext)
+ async def _solve_pow(self, url: AbsoluteHttpURL, pow: ProofOfWork) -> int: # noqa: A002
+ try:
+ async with self._startup_lock:
+ self.log.warning("Solving proof of work challenge for %s\n%s", url, dict(pow))
+ solution = await multi_process.async_race(_pow_worker, pow.pow_challenge, pow.pow_diff)
+
+ except TimeoutError:
+ msg = f"Unable to solve challenge {pow.pow_challenge} after {multi_process.TIMEOUT.get()} seconds"
+ raise TimeoutError(msg) from None
+
+ self.log.debug("Solved pow %s after %s seconds", pow.pow_challenge, solution.elapsed)
+ return solution.value
+
+ async def request_pow_soup(self, url: AbsoluteHttpURL) -> bs4.BeautifulSoup:
+ soup = await self.request_soup(url)
+ if form := soup.select_one("form#pow-form"):
+ pow = ProofOfWork.parse(form) # noqa: A001
+ nonce = await self._solve_pow(url, pow)
+ soup = await self.request_soup(
+ url,
+ "POST",
+ headers={"Referer": str(url), "Origin": "https://fileditchfiles.me"},
+ data=dict(pow) | {"pow_nonce": nonce},
+ )
+ if soup.select_one("form#pow-form"):
+ raise ScrapeError(422, "Proof of work verification failed")
+ return soup
+
+
[email protected](slots=True)
+class ProofOfWork(DictDataclass):
+ orig_ref: str
+ pow_challenge: str
+ pow_ts: int
+ pow_diff: int
+ pow_sig: str
+
+ def __post_init__(self) -> None:
+ self.pow_ts = int(self.pow_ts)
+ self.pow_diff = int(self.pow_diff)
+
+ @classmethod
+ def parse(cls, form: bs4.Tag) -> Self:
+ def inputs():
+ for field in css.iselect(form, "input[name]"):
+ yield css.attr(field, "name"), css.attr(field, "value")
+
+ return cls.from_dict(dict(inputs()))
+
+
+def _pow_worker(worker_idx: int, _: int, challenge: str, difficulty: int) -> int | None:
+ nonce = worker_idx * 15_000
+ while True:
+ checksum = hashlib.sha256(f"{challenge}:{nonce}".encode()).digest()
+ if _is_valid_solution(checksum, difficulty):
+ return nonce
+ nonce += 1
+
+
+def _is_valid_solution(checksum: bytes, difficulty: int) -> bool:
+ idx, rem = difficulty >> 3, difficulty & 7
+ if idx and checksum[:idx] != b"\x00" * idx:
+ return False
+ if rem:
+ return (checksum[idx] & (0xFF << (8 - rem) & 0xFF)) == 0
+ return True
+
-def _extract_dl_url(soup: BeautifulSoup) -> AbsoluteHttpURL:
+def _extract_dl_url(soup: bs4.BeautifulSoup) -> AbsoluteHttpURL:
js_join = '].join("")'
js_text = css.select_text(soup, f"script:-soup-contains-own('{js_join}')")
array = extr_text(js_text, "= [", js_join)
diff --git a/cyberdrop_dl/database/history.py b/cyberdrop_dl/database/history.py
index 118c5d861..f62018ed3 100644
--- a/cyberdrop_dl/database/history.py
+++ b/cyberdrop_dl/database/history.py
@@ -189,7 +189,7 @@ async def _fix_domains(db_conn: aiosqlite.Connection) -> None:
async def _fix_referers(db_conn: aiosqlite.Connection) -> None:
- from cyberdrop_dl.crawlers import bunkr, cyberdrop, goonbox, redgifs, turbovid
+ from cyberdrop_dl.crawlers import bunkr, cyberdrop, fileditch, goonbox, redgifs, turbovid
def try_wrap[T](fn: Callable[..., T]) -> Callable[..., T]:
def call(*args: Any, **kwargs: Any) -> T:
@@ -207,6 +207,11 @@ async def _fix_referers(db_conn: aiosqlite.Connection) -> None:
("FIX_REDGIFS_REFERER", redgifs.fix_redgifs_referer, "redgifs"),
("FIX_GOONBOX_REFERER", _generic_fix_referer(goonbox.GoonBoxCrawler), "goonbox"),
("FIX_CYBERDROP_REFERER", _generic_fix_referer(cyberdrop.CyberdropCrawler), "cyberdrop"),
+ (
+ "FIX_FILEDITCH_REFERER",
+ _generic_fix_referer(fileditch.FileditchCrawler),
+ fileditch.FileditchCrawler.DOMAIN,
+ ),
("FIX_TURBOVID_REFERER", turbovid.fix_turbovid_referer, "turbovid"),
("FIX_BUNKR_REFERER", bunkr.fix_db_referer, "bunkr"),
]:
diff --git a/cyberdrop_dl/database/schema.py b/cyberdrop_dl/database/schema.py
index a14a940cf..9f9d69f77 100644
--- a/cyberdrop_dl/database/schema.py
+++ b/cyberdrop_dl/database/schema.py
@@ -32,7 +32,7 @@ class Version(NamedTuple):
return ".".join(map(str, self))
-CURRENT_VERSION = Version(10, 1, 0)
+CURRENT_VERSION = Version(10, 2, 1)
REQUIRED_VERSION = Version(9, 15, 0)
logger = logging.getLogger(__name__)
diff --git a/cyberdrop_dl/ddos_guard.py b/cyberdrop_dl/ddos_guard.py
index 9213f15c1..a19fbe8be 100644
--- a/cyberdrop_dl/ddos_guard.py
+++ b/cyberdrop_dl/ddos_guard.py
@@ -4,13 +4,12 @@ import asyncio
import dataclasses
import hashlib
import json
-import os
-import sys
from typing import TYPE_CHECKING, Protocol, final, override
import yarl
from bs4 import BeautifulSoup
+from cyberdrop_dl import multi_process
from cyberdrop_dl.exceptions import DDOSGuardError
if TYPE_CHECKING:
@@ -184,36 +183,16 @@ class Anubis(DDosGuard):
return await asyncio.to_thread(cls._solve, challenge)
@classmethod
- def _solve(cls, challenge: _AnubisChallenge, *, timeout: int | None = 30) -> _AnubisSolution:
- import multiprocessing as mp
- import time
- from concurrent.futures import ProcessPoolExecutor, as_completed
-
- max_workers = max(cpu_count() // 2, 1)
- start_time = time.monotonic()
-
- with ProcessPoolExecutor(max_workers=max_workers, mp_context=mp.get_context("spawn")) as executor:
- futures = [
- executor.submit(_anubis_worker, idx, max_workers, challenge.data, challenge.difficulty)
- for idx in range(max_workers)
- ]
-
- try:
- for future in as_completed(futures, timeout=timeout):
- result = future.result()
- if result is not None:
- nonce, checksum = result
- elapsed = time.monotonic() - start_time
- executor.shutdown(wait=False, cancel_futures=True)
- return _AnubisSolution(
- challenge.id, nonce, checksum, challenge.difficulty, max_workers, elapsed
- )
-
- except TimeoutError:
- pass
-
- elapsed = time.monotonic() - start_time
- raise DDOSGuardError(f"Unable to solve Anubis challenge after {elapsed:0.2f} seconds: {challenge}")
+ def _solve(cls, challenge: _AnubisChallenge, *, timeout: float = 30.0) -> _AnubisSolution:
+ try:
+ with multi_process.ctx(timeout=timeout):
+ result = multi_process.race(_anubis_worker, challenge.data, challenge.difficulty)
+ except TimeoutError:
+ msg = f"Unable to solve Anubis challenge after {timeout:0.2f} seconds: {challenge}"
+ raise DDOSGuardError(msg) from None
+
+ nonce, checksum = result.value
+ return _AnubisSolution(challenge.id, nonce, checksum, challenge.difficulty, result.elapsed)
@dataclasses.dataclass(slots=True, frozen=True)
@@ -229,7 +208,6 @@ class _AnubisSolution:
nonce: int
hash: str
difficulty: int
- workers: int = dataclasses.field(compare=False)
total_time: float = dataclasses.field(compare=False)
@property
@@ -251,15 +229,3 @@ def _anubis_worker(start: int, step: int, challenge: str, difficulty: int) -> tu
if checksum.startswith(target):
return nonce, checksum
nonce += step
-
-
-if sys.platform not in {"win32", "darwin"} and hasattr(os, "sched_getaffinity"):
-
- def cpu_count() -> int:
- return len(os.sched_getaffinity(0))
-
-
-else:
-
- def cpu_count() -> int:
- return os.cpu_count() or 1
diff --git a/cyberdrop_dl/multi_process.py b/cyberdrop_dl/multi_process.py
new file mode 100644
index 000000000..7fe184251
--- /dev/null
+++ b/cyberdrop_dl/multi_process.py
@@ -0,0 +1,81 @@
+from __future__ import annotations
+
+import contextlib
+import dataclasses
+import os
+import sys
+from contextvars import ContextVar
+from typing import TYPE_CHECKING, Concatenate
+
+from cyberdrop_dl import aio
+from cyberdrop_dl.constants import MISSING
+from cyberdrop_dl.utils import enter_context
+
+if TYPE_CHECKING:
+ from collections.abc import Callable, Generator
+
+TIMEOUT: ContextVar[float | None] = ContextVar("TIMEOUT", default=30.0)
+MAX_WORKERS: ContextVar[int | None] = ContextVar("MAX_WORKERS", default=None)
+
+
[email protected](slots=True)
+class RaceResult[T]:
+ value: T
+ elapsed: float
+ workers: int
+
+
+def ctx(
+ max_workers: int | None | MISSING = MISSING, # pyright: ignore[reportInvalidTypeForm]
+ timeout: float | None | MISSING = MISSING, # pyright: ignore[reportInvalidTypeForm]
+) -> Generator[None]:
+ with contextlib.ExitStack() as stack:
+ if max_workers is not MISSING:
+ stack.enter_context(enter_context(MAX_WORKERS, max_workers))
+ if timeout is not MISSING:
+ stack.enter_context(enter_context(TIMEOUT, timeout))
+ yield
+
+
+def race[**P, R](
+ worker: Callable[Concatenate[int, int, P], R | None], *args: P.args, **kwargs: P.kwargs
+) -> RaceResult[R]:
+ """Execute a worker function across multiple processes in a race condition, returning the first non-None result.
+
+ All other processes are cancelled on exit.
+ """
+ import multiprocessing as mp
+ import time
+ from concurrent.futures import ProcessPoolExecutor, as_completed
+
+ cpu_limit = max(cpu_count() // 2, 1)
+ max_workers = MAX_WORKERS.get()
+ max_workers = cpu_limit if not max_workers else min(max_workers, cpu_limit)
+ start_time = time.monotonic()
+
+ with ProcessPoolExecutor(max_workers=max_workers, mp_context=mp.get_context("spawn")) as executor:
+ futures = [executor.submit(worker, idx, max_workers, *args, **kwargs) for idx in range(max_workers)]
+
+ for future in as_completed(futures, timeout=TIMEOUT.get()):
+ result = future.result()
+ if result is not None:
+ elapsed = time.monotonic() - start_time
+ executor.shutdown(wait=False, cancel_futures=True)
+ return RaceResult(result, elapsed, max_workers)
+
+ raise RuntimeError("None of the workers found a solution")
+
+
+async_race = aio.to_thread(race)
+
+if sys.platform not in {"win32", "darwin"} and hasattr(os, "sched_getaffinity"):
+
+ def cpu_count() -> int:
+ return len(os.sched_getaffinity(0))
+
+
+else:
+
+ def cpu_count() -> int:
+ return os.cpu_count() or 1
diff --git a/cyberdrop_dl/utils/dataclass.py b/cyberdrop_dl/utils/dataclass.py
index 2f14563b1..9578c8558 100644
--- a/cyberdrop_dl/utils/dataclass.py
+++ b/cyberdrop_dl/utils/dataclass.py
@@ -7,7 +7,7 @@ from cyberdrop_dl.constants import MISSING
from cyberdrop_dl.utils import fast_cache
if TYPE_CHECKING:
- from collections.abc import Mapping
+ from collections.abc import Iterator, Mapping
class _DataClass(Protocol):
@@ -18,12 +18,12 @@ _FIELDS_CACHE: dict[type, tuple[str, ...]] = {}
@fast_cache
-def _fields(cls: type[_DataClass]) -> tuple[str, ...]:
+def _fields_names(cls: type[_DataClass]) -> tuple[str, ...]:
return tuple(f.name for f in dataclasses.fields(cls) if f.init)
def filter_data[DataClassT: _DataClass](cls: type[DataClassT], data: Mapping[str, Any], /) -> dict[str, Any]:
- return {name: value for name in _fields(cls) if (value := data.get(name, MISSING)) is not MISSING}
+ return {name: value for name in _fields_names(cls) if (value := data.get(name, MISSING)) is not MISSING}
def deserialize[DataClassT: _DataClass](
@@ -37,6 +37,10 @@ def deserialize[DataClassT: _DataClass](
class DictDataclass(_DataClass, Protocol):
+ def __iter__(self) -> Iterator[tuple[str, Any]]:
+ for field_name in _fields_names(type(self)):
+ yield field_name, getattr(self, field_name)
+
filter_dict = classmethod(filter_data) # pyright: ignore[reportUnannotatedClassAttribute]
@classmethod
diff --git a/pyproject.toml b/pyproject.toml
index 1baa4f099..dde23fa79 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "cyberdrop-dl-patched"
-version = "10.2.0"
+version = "10.2.1"
authors = [{name = "Jacob B", email = "[email protected]"}]
classifiers = [
"Development Status :: 5 - Production/Stable",
diff --git a/tests/crawlers/test_cases/fileditch.py b/tests/crawlers/test_cases/fileditch.py
index 7cb7a3320..3bdd15d2e 100644
--- a/tests/crawlers/test_cases/fileditch.py
+++ b/tests/crawlers/test_cases/fileditch.py
@@ -6,7 +6,7 @@ TEST_CASES = [
{
"url": "re:/b71/FrmLzfLKUHBWDTQfqaTZ.mp4?md5=",
"filename": "FrmLzfLKUHBWDTQfqaTZ.mp4",
- "referer": "https://fileditchfiles.me/file.php?f=/b71/FrmLzfLKUHBWDTQfqaTZ.mp4",
+ "referer": "https://fileditchfiles.me/b71/FrmLzfLKUHBWDTQfqaTZ.mp4",
"download_folder": "re:Loose Files (Fileditch)",
"uploaded_at": None,
}
@@ -18,7 +18,7 @@ TEST_CASES = [
"results": [
{
"url": "re:/b70/jRuBeGZlRoBWPurUARg.mp4?md5=",
- "referer": "https://fileditchfiles.me/file.php?f=/b70/jRuBeGZlRoBWPurUARg.mp4",
+ "referer": "https://fileditchfiles.me/b70/jRuBeGZlRoBWPurUARg.mp4",
"download_folder": "re:Loose Files (Fileditch)",
"uploaded_at": None,
}
diff --git a/tests/test_ddos_guard.py b/tests/test_ddos_guard.py
index 3ff7b9c4e..edf5a1cac 100644
--- a/tests/test_ddos_guard.py
+++ b/tests/test_ddos_guard.py
@@ -58,7 +58,6 @@ async def test_solve_anubis_challenge() -> None:
id="019abb13-2859-7587-bec3-16e0a3f67ce9",
nonce=1676094,
hash="00000e426afc08534b13bb3f75bad02dc20d73d70674b9dc174416cc7d3685e6",
- workers=2,
difficulty=5,
total_time=0,
)
diff --git a/uv.lock b/uv.lock
index 34156ff45..368ce21f1 100644
--- a/uv.lock
+++ b/uv.lock
@@ -607,7 +607,7 @@ wheels = [
[[package]]
name = "cyberdrop-dl-patched"
-version = "10.2.0"
+version = "10.2.1"
source = { editable = "." }
dependencies = [
{ name = "aiodns", marker = "sys_platform != 'android' and sys_platform != 'win32'" },