diff --git a/README.md b/README.md index 9748858..3656e84 100644 --- a/README.md +++ b/README.md @@ -87,6 +87,8 @@ CapmonsterClient(api_key, timeout=30.0, max_retries=120, retry_delay=2.0) | `create_task(task)` | Create a task, returns `task_id` | | `join_task_result(task_id)` | Poll until result is ready | | `get_task_result(task_id)` | Single poll (no waiting) | +| `solve_detailed(task)` | Like `solve`, but returns a `TaskResult` with `solution` and `cost` | +| `join_task_result_detailed(task_id)` / `get_task_result_detailed(task_id)` | Same, for polling | | `get_balance()` | Get account balance | | `get_user_agent()` | Get current valid User-Agent string | | `report_incorrect_image(task_id)` | Report bad image captcha solution | @@ -106,14 +108,14 @@ Both sync and async context managers are supported for proper connection cleanup | reCAPTCHA v2 Enterprise | `RecaptchaV2EnterpriseTask` | Optional | | reCAPTCHA v3 | `RecaptchaV3Task` | No | | reCAPTCHA v3 Enterprise | `RecaptchaV3EnterpriseTask` | No | -| reCAPTCHA Click | `RecaptchaClickTask` | Optional | +| reCAPTCHA Click | `RecaptchaClickTask` (deprecated, use `ComplexImageRecaptchaTask`) | Optional | ### Cloudflare | CAPTCHA Type | Class | Proxy | |---|---|---| | Turnstile | `TurnstileTask` | No | -| Turnstile Challenge (cf_clearance) | `TurnstileCloudFlareTask` | Required | +| Turnstile Challenge (token / cf_clearance) | `TurnstileCloudFlareTask` | Optional / Required | | Turnstile Waiting Room | `TurnstileWaitingRoomTask` | Required | ### Image-Based @@ -121,7 +123,7 @@ Both sync and async context managers are supported for proper connection cleanup | CAPTCHA Type | Class | Proxy | |---|---|---| | Image-to-Text OCR | `ImageToTextTask` | No | -| Complex Image (reCAPTCHA grid) | `ComplexImageRecaptchaTask` | No | +| Complex Image (reCAPTCHA click/grid) | `ComplexImageRecaptchaTask` | No | | Complex Image Recognition | `ComplexImageRecognitionTask` | No | ### Behavioral / Interactive @@ -130,8 +132,11 @@ Both sync and async context managers are supported for proper connection cleanup |---|---|---| | GeeTest v3 | `GeeTestV3Task` | Optional | | GeeTest v4 | `GeeTestV4Task` | Optional | -| FunCaptcha (Arkose Labs) | `FunCaptchaTask` | Optional | -| Hunt | `HuntTask` | Optional | +| FunCaptcha (Arkose Labs) | `FunCaptchaTask` | Required | +| Hunt | `HuntTask` | Required | +| Alibaba | `AlibabaTask` | Optional | +| Friendly Captcha | `FriendlyTask` | Optional | +| ARCaptcha | `ARCaptchaTask` | No | ### Enterprise Protection @@ -147,8 +152,11 @@ Both sync and async context managers are supported for proper connection cleanup | CAPTCHA Type | Class | Proxy | |---|---|---| | Binance | `BinanceTask` | Required | -| Temu | `TemuTask` | No | -| TenDI | `TenDITask` | Required | +| Temu | `TemuTask` (deprecated) | No | +| TenDI | `TenDITask` | Optional | +| FengkongCloud | `FengkongCloudTask` | No | +| HeyTap | `HeyTapTask` | No | +| Proton | `ProtonTask` | Required | ### Other @@ -156,7 +164,7 @@ Both sync and async context managers are supported for proper connection cleanup |---|---|---| | Altcha | `AltchaTask` | No | | Basilisk | `BasiliskTask` | No | -| Castle | `CastleTask` | No | +| Castle | `CastleTask` (deprecated) | No | | MTCaptcha | `MTCaptchaTask` | Optional | | Prosopo | `ProsopoTask` | Optional | | Yidun | `YidunTask` | Optional | diff --git a/docs/examples.md b/docs/examples.md index 3257d14..dd19d0a 100644 --- a/docs/examples.md +++ b/docs/examples.md @@ -628,7 +628,7 @@ async def main(): websiteURL="https://example.com", metadata=ImpervaTaskMetadata( incapsulaScriptUrl="https://example.com/js.inc", - incapsulaCookie="visid_incap_12345=...", + incapsulaCookies="visid_incap_12345=...", ) ) task_id = await client.create_task_async(task) @@ -646,7 +646,7 @@ task_id = client.create_task(ImpervaTask( websiteURL="https://example.com", metadata=ImpervaTaskMetadata( incapsulaScriptUrl="https://example.com/js.inc", - incapsulaCookie="visid_incap_12345=...", + incapsulaCookies="visid_incap_12345=...", ) )) result = client.get_task_result(task_id) @@ -815,6 +815,10 @@ print(result) ## Temu +!!!warning Deprecated +`TemuTask` emits a `DeprecationWarning` and will be removed in 6.0: Temu is no longer in the CapMonster Cloud docs. +!!! + Used to bypass CAPTCHA challenges on Temu using extracted cookies. +++ Async @@ -1023,7 +1027,11 @@ print(result) --- -## Castle [!badge text="NEW" variant="success"] +## Castle + +!!!warning Deprecated +`CastleTask` emits a `DeprecationWarning` and will be removed in 6.0: Castle is no longer in the CapMonster Cloud docs. +!!! Used for solving Castle challenges. @@ -1118,3 +1126,265 @@ result = client.get_task_result(task_id) print(result) ``` +++ + +--- + +## Hunt [!badge text="NEW" variant="success"] + +Solves Hunt captcha through `widgetUrl` (or `data` with the site's `meta.token`). Proxy is required. + +!!! +The old `HuntTask(websiteKey=...)` form is deprecated; it still works but emits a `DeprecationWarning`. +!!! + ++++ Async +```python +import asyncio +from capmonster_python import CapmonsterClient, HuntTask, HuntMetadata, ProxyPayload + +async def main(): + async with CapmonsterClient(api_key="") as client: + task = HuntTask( + websiteURL="https://example.com/page-with-hunt", + metadata=HuntMetadata( + apiGetLib="https://example.com/hd-api/external/apps//api.js", + widgetUrl="https://captcha.example.com/widget?hash=" + ), + proxy=ProxyPayload(proxyType="http", proxyAddress="1.2.3.4", proxyPort=8080, + proxyLogin="", proxyPassword="") + ) + result = await client.solve_async(task) + print(result) + +asyncio.run(main()) +``` ++++ Sync +```python +from capmonster_python import CapmonsterClient, HuntTask, HuntMetadata, ProxyPayload + +with CapmonsterClient(api_key="") as client: + task = HuntTask( + websiteURL="https://example.com/page-with-hunt", + metadata=HuntMetadata( + apiGetLib="https://example.com/hd-api/external/apps//api.js", + widgetUrl="https://captcha.example.com/widget?hash=" + ), + proxy=ProxyPayload(proxyType="http", proxyAddress="1.2.3.4", proxyPort=8080, + proxyLogin="", proxyPassword="") + ) + result = client.solve(task) + print(result) +``` ++++ + +--- + +## Alibaba [!badge text="NEW" variant="success"] + +Solves Alibaba captcha. Use `punishUrl` instead of `sceneId`/`prefix` for sites that return a `/punish` URL. + ++++ Async +```python +import asyncio +from capmonster_python import CapmonsterClient, AlibabaTask, AlibabaMetadata + +async def main(): + async with CapmonsterClient(api_key="") as client: + task = AlibabaTask( + websiteURL="https://www.example.com", + metadata=AlibabaMetadata(sceneId="", prefix="") + ) + result = await client.solve_async(task) + print(result) + +asyncio.run(main()) +``` ++++ Sync +```python +from capmonster_python import CapmonsterClient, AlibabaTask, AlibabaMetadata + +with CapmonsterClient(api_key="") as client: + task = AlibabaTask( + websiteURL="https://www.example.com", + metadata=AlibabaMetadata(sceneId="", prefix="") + ) + result = client.solve(task) + print(result) +``` ++++ + +--- + +## Friendly Captcha [!badge text="NEW" variant="success"] + +Solves Friendly Captcha V1 and V2. + ++++ Async +```python +import asyncio +from capmonster_python import CapmonsterClient, FriendlyTask, FriendlyMetadata + +async def main(): + async with CapmonsterClient(api_key="") as client: + task = FriendlyTask( + websiteURL="https://example.com", + websiteKey="", + metadata=FriendlyMetadata(apiGetLib="https://cdn.jsdelivr.net/npm/@friendlycaptcha/sdk@X.Y.Z/site.min.js") + ) + result = await client.solve_async(task) + print(result) + +asyncio.run(main()) +``` ++++ Sync +```python +from capmonster_python import CapmonsterClient, FriendlyTask, FriendlyMetadata + +with CapmonsterClient(api_key="") as client: + task = FriendlyTask( + websiteURL="https://example.com", + websiteKey="", + metadata=FriendlyMetadata(apiGetLib="https://cdn.jsdelivr.net/npm/@friendlycaptcha/sdk@X.Y.Z/site.min.js") + ) + result = client.solve(task) + print(result) +``` ++++ + +--- + +## FengkongCloud [!badge text="NEW" variant="success"] + +Solves FengkongCloud captcha. No proxy. + ++++ Async +```python +import asyncio +from capmonster_python import CapmonsterClient, FengkongCloudTask, FengkongCloudMetadata + +async def main(): + async with CapmonsterClient(api_key="") as client: + task = FengkongCloudTask( + websiteURL="https://example.com", + websiteKey="", + metadata=FengkongCloudMetadata(apiJsUrl="https://castatic.fengkongcloud.com/pr/vX.X.X/smcp.min.js") + ) + result = await client.solve_async(task) + print(result) + +asyncio.run(main()) +``` ++++ Sync +```python +from capmonster_python import CapmonsterClient, FengkongCloudTask, FengkongCloudMetadata + +with CapmonsterClient(api_key="") as client: + task = FengkongCloudTask( + websiteURL="https://example.com", + websiteKey="", + metadata=FengkongCloudMetadata(apiJsUrl="https://castatic.fengkongcloud.com/pr/vX.X.X/smcp.min.js") + ) + result = client.solve(task) + print(result) +``` ++++ + +--- + +## ARCaptcha [!badge text="NEW" variant="success"] + +Solves ARCaptcha. No proxy. + ++++ Async +```python +import asyncio +from capmonster_python import CapmonsterClient, ARCaptchaTask + +async def main(): + async with CapmonsterClient(api_key="") as client: + task = ARCaptchaTask(websiteURL="https://example.com", websiteKey="") + result = await client.solve_async(task) + print(result) + +asyncio.run(main()) +``` ++++ Sync +```python +from capmonster_python import CapmonsterClient, ARCaptchaTask + +with CapmonsterClient(api_key="") as client: + task = ARCaptchaTask(websiteURL="https://example.com", websiteKey="") + result = client.solve(task) + print(result) +``` ++++ + +--- + +## HeyTap [!badge text="NEW" variant="success"] + +Solves HeyTap captcha. No proxy. + ++++ Async +```python +import asyncio +from capmonster_python import CapmonsterClient, HeyTapTask + +async def main(): + async with CapmonsterClient(api_key="") as client: + task = HeyTapTask(websiteURL="https://example.com", websiteKey="") + result = await client.solve_async(task) + print(result) + +asyncio.run(main()) +``` ++++ Sync +```python +from capmonster_python import CapmonsterClient, HeyTapTask + +with CapmonsterClient(api_key="") as client: + task = HeyTapTask(websiteURL="https://example.com", websiteKey="") + result = client.solve(task) + print(result) +``` ++++ + +--- + +## Proton Captcha [!badge text="NEW" variant="success"] + +Solves Proton Captcha. Proxy is required. + ++++ Async +```python +import asyncio +from capmonster_python import CapmonsterClient, ProtonTask, ProtonMetadata, ProxyPayload + +async def main(): + async with CapmonsterClient(api_key="") as client: + task = ProtonTask( + websiteURL="https://example.com/", + metadata=ProtonMetadata(HumanVerificationToken="", pageAction="login"), + proxy=ProxyPayload(proxyType="http", proxyAddress="1.2.3.4", proxyPort=8080, + proxyLogin="", proxyPassword="") + ) + result = await client.solve_async(task) + print(result) + +asyncio.run(main()) +``` ++++ Sync +```python +from capmonster_python import CapmonsterClient, ProtonTask, ProtonMetadata, ProxyPayload + +with CapmonsterClient(api_key="") as client: + task = ProtonTask( + websiteURL="https://example.com/", + metadata=ProtonMetadata(HumanVerificationToken="", pageAction="login"), + proxy=ProxyPayload(proxyType="http", proxyAddress="1.2.3.4", proxyPort=8080, + proxyLogin="", proxyPassword="") + ) + result = client.solve(task) + print(result) +``` ++++ diff --git a/docs/index.md b/docs/index.md index f4a9a64..8d690d6 100644 --- a/docs/index.md +++ b/docs/index.md @@ -42,10 +42,11 @@ Image-to-Text, and more — with both sync and async support out of the box. | **reCAPTCHA** | V2, V2 Enterprise, V3, V3 Enterprise [!badge text="NEW" variant="success"] | | **Turnstile** | Token, CloudFlare (cf_clearance), Waiting Room [!badge text="NEW" variant="success"] | | **GeeTest** | V3, V4 | -| **Image-Based** | ImageToText, ComplexImageRecaptcha, ComplexImageRecognition | +| **Image-Based** | ImageToText, ComplexImageRecaptcha (reCAPTCHA click), ComplexImageRecognition | | **Enterprise** | DataDome, Imperva, Amazon WAF [!badge text="NEW" variant="success"] | -| **Platform** | Binance, Temu, TenDI | -| **Other** | Prosopo, Basilisk, FunCaptcha [!badge text="NEW" variant="success"], MTCaptcha [!badge text="NEW" variant="success"], Yidun [!badge text="NEW" variant="success"], Altcha [!badge text="NEW" variant="success"], Castle [!badge text="NEW" variant="success"], TSPD [!badge text="NEW" variant="success"] | +| **Platform** | Binance, TenDI, Alibaba [!badge text="NEW" variant="success"], HeyTap [!badge text="NEW" variant="success"], Proton [!badge text="NEW" variant="success"], FengkongCloud [!badge text="NEW" variant="success"] | +| **Other** | Prosopo, Basilisk, FunCaptcha [!badge text="NEW" variant="success"], MTCaptcha [!badge text="NEW" variant="success"], Yidun [!badge text="NEW" variant="success"], Altcha [!badge text="NEW" variant="success"], TSPD [!badge text="NEW" variant="success"], Hunt, Friendly Captcha [!badge text="NEW" variant="success"], ARCaptcha [!badge text="NEW" variant="success"] | +| **Deprecated** | Temu, Castle, RecaptchaClickTask (removed in 6.0) | --- diff --git a/docs/reference/alibaba.md b/docs/reference/alibaba.md new file mode 100644 index 0000000..8f8cbc7 --- /dev/null +++ b/docs/reference/alibaba.md @@ -0,0 +1,29 @@ +# Alibaba [!badge text="NEW" variant="success"] + +Solves Alibaba captcha and Alibaba WAF challenges. + +**API type:** `CustomTask` (with `class: "alibaba"`) + +| Parameter | Type | Default | Description | +|-----------|------|---------|-------------| +| `websiteURL` | `str` | **required** | Full URL of the page with the captcha. | +| `metadata` | `AlibabaMetadata` | **required** | Alibaba-specific metadata. | +| `userAgent` | `str \| None` | `None` | Browser User-Agent string. | +| `proxy` | `ProxyPayload \| None` | `None` | Proxy settings. | + +## AlibabaMetadata + +`sceneId` and `prefix` are required unless `punishUrl` is set. Pass the other fields only if the website uses them. + +| Parameter | Type | Default | Description | +|-----------|------|---------|-------------| +| `sceneId` | `str \| None` | `None` | Captcha scenario identifier. | +| `prefix` | `str \| None` | `None` | Captcha initialization parameter (subdomain of the `captcha-open` URL). | +| `userId` | `str \| None` | `None` | User or session identifier on the website side. | +| `userUserId` | `str \| None` | `None` | Secondary user identifier. | +| `verifyType` | `str \| None` | `None` | Verification mechanism version, e.g. `"1.0"`. | +| `region` | `str \| None` | `None` | Region that processes the captcha, e.g. `"cn"` or `"sgp"`. | +| `UserCertifyId` | `str \| None` | `None` | Verification ID of the captcha session. | +| `apiGetLib` | `str \| None` | `None` | Link to the captcha JS library used by the website. | +| `punishUrl` | `str \| None` | `None` | Full URL of the `/punish` verification page, including its query string. | +| `cookieRequired` | `bool \| None` | `None` | Return cookies with the solution (Alibaba WAF). | diff --git a/docs/reference/arcaptcha.md b/docs/reference/arcaptcha.md new file mode 100644 index 0000000..70a026b --- /dev/null +++ b/docs/reference/arcaptcha.md @@ -0,0 +1,12 @@ +# ARCaptcha [!badge text="NEW" variant="success"] + +Solves ARCaptcha challenges. No proxy. + +**API type:** `ArCaptchaTask` + +| Parameter | Type | Default | Description | +|-----------|------|---------|-------------| +| `websiteURL` | `str` | **required** | Address of the main page with the captcha. | +| `websiteKey` | `str` | **required** | The `siteKey` value found on the page. | +| `isInvisible` | `bool \| None` | `None` | Set to `True` for invisible ARCaptcha. | +| `userAgent` | `str \| None` | `None` | Browser User-Agent string. | diff --git a/docs/reference/castle.md b/docs/reference/castle.md index a307aee..253ac30 100644 --- a/docs/reference/castle.md +++ b/docs/reference/castle.md @@ -1,5 +1,9 @@ # Castle +!!!warning Deprecated +`CastleTask` emits a `DeprecationWarning` and will be removed in 6.0: Castle is no longer in the CapMonster Cloud docs. +!!! + Solves Castle challenges. **API type:** `CustomTask` (with `class: "Castle"`) diff --git a/docs/reference/client.md b/docs/reference/client.md index 66965dc..523d49b 100644 --- a/docs/reference/client.md +++ b/docs/reference/client.md @@ -122,6 +122,36 @@ async def solve_async(self, task: TaskPayload, callback_url: str | None = None) --- +### `get_task_result_detailed` / `join_task_result_detailed` / `solve_detailed` [!badge text="NEW" variant="success"] + +Same as `get_task_result`, `join_task_result` and `solve`, but return a `TaskResult` with the task's status and cost +as well as its solution. The methods above keep returning only the solution dictionary. + +```python +def get_task_result_detailed(self, task_id: int) -> TaskResult +def join_task_result_detailed(self, task_id: int) -> TaskResult +def solve_detailed(self, task: TaskPayload, callback_url: str | None = None) -> TaskResult +# async variants: get_task_result_detailed_async, join_task_result_detailed_async, solve_detailed_async +``` + +**Returns:** `TaskResult` + +| Attribute | Type | Description | +|-----------|------|-------------| +| `status` | `str` | `"processing"` or `"ready"`. | +| `solution` | `dict` | The solution; `{}` while the task is processing. | +| `cost` | `float \| None` | Cost of the task in USD; only set when the task is ready. | + +```python +from capmonster_python import CapmonsterClient, TurnstileTask + +with CapmonsterClient(api_key="YOUR_API_KEY") as client: + result = client.solve_detailed(TurnstileTask(websiteURL="https://example.com", websiteKey="0x4AAAAAAA")) + print(result.solution["token"], result.cost) +``` + +--- + ### `report_incorrect_image` Reports an incorrect image captcha solution. diff --git a/docs/reference/datadome.md b/docs/reference/datadome.md index fd8af5e..814ad7e 100644 --- a/docs/reference/datadome.md +++ b/docs/reference/datadome.md @@ -9,7 +9,7 @@ Solves DataDome captcha challenges. | `websiteURL` | `str` | **required** | Address of the page with the captcha. | | `metadata` | `DataDomeMetadata` | **required** | Additional captcha metadata. | | `userAgent` | `str \| None` | `None` | Browser User-Agent string. | -| `proxy` | `ProxyPayload \| None` | `None` | Proxy settings. | +| `proxy` | `ProxyPayload \| None` | `None` | Proxy settings. Required by the API; a `UserWarning` is emitted without it. | ## DataDomeMetadata @@ -18,6 +18,7 @@ Solves DataDome captcha challenges. | `datadomeCookie` | `str` | **required** | DataDome cookies from `document.cookie`. | | `htmlPageBase64` | `str \| None` | `None` | Base64-encoded captcha page data. | | `captchaUrl` | `str \| None` | `None` | Link to the captcha (e.g. `https://geo.captcha-delivery.com/captcha/?initialCid=...`). | +| `datadomeVersion` | `str \| None` | `None` | DataDome script version, if the site requires it. | !!!warning Exactly one of `htmlPageBase64` or `captchaUrl` must be provided (not both, not neither). diff --git a/docs/reference/fengkongcloud.md b/docs/reference/fengkongcloud.md new file mode 100644 index 0000000..040edc2 --- /dev/null +++ b/docs/reference/fengkongcloud.md @@ -0,0 +1,18 @@ +# FengkongCloud [!badge text="NEW" variant="success"] + +Solves FengkongCloud captcha challenges. No proxy. + +**API type:** `CustomTask` (with `class: "fengkongcloud"`) + +| Parameter | Type | Default | Description | +|-----------|------|---------|-------------| +| `websiteURL` | `str` | **required** | Address of the main page with the captcha. | +| `websiteKey` | `str` | **required** | The `siteKey` value found on the page. | +| `metadata` | `FengkongCloudMetadata \| None` | `None` | Optional metadata. | +| `userAgent` | `str \| None` | `None` | Browser User-Agent string. | + +## FengkongCloudMetadata + +| Parameter | Type | Default | Description | +|-----------|------|---------|-------------| +| `apiJsUrl` | `str \| None` | `None` | Link to `smcp.min.js`. | diff --git a/docs/reference/friendly.md b/docs/reference/friendly.md new file mode 100644 index 0000000..d5dce7f --- /dev/null +++ b/docs/reference/friendly.md @@ -0,0 +1,19 @@ +# Friendly Captcha [!badge text="NEW" variant="success"] + +Solves Friendly Captcha (V1 and V2). + +**API type:** `CustomTask` (with `class: "friendly"`) + +| Parameter | Type | Default | Description | +|-----------|------|---------|-------------| +| `websiteURL` | `str` | **required** | Full URL of the page with the captcha. | +| `websiteKey` | `str` | **required** | Friendly Captcha site key. | +| `metadata` | `FriendlyMetadata` | **required** | Friendly-specific metadata. | +| `userAgent` | `str \| None` | `None` | Browser User-Agent string. | +| `proxy` | `ProxyPayload \| None` | `None` | Proxy settings. | + +## FriendlyMetadata + +| Parameter | Type | Default | Description | +|-----------|------|---------|-------------| +| `apiGetLib` | `str` | **required** | V1: `widget.module.min.js` of `friendly-challenge`; V2: the `site.min.js` loaded on the page. | diff --git a/docs/reference/heytap.md b/docs/reference/heytap.md new file mode 100644 index 0000000..018dce6 --- /dev/null +++ b/docs/reference/heytap.md @@ -0,0 +1,18 @@ +# HeyTap [!badge text="NEW" variant="success"] + +Solves HeyTap captcha challenges. No proxy. + +**API type:** `CustomTask` (with `class: "heytap"`) + +| Parameter | Type | Default | Description | +|-----------|------|---------|-------------| +| `websiteURL` | `str` | **required** | Address of the main page with the captcha. | +| `websiteKey` | `str` | **required** | The `siteKey` value found on the page. | +| `metadata` | `HeyTapMetadata \| None` | `None` | Optional metadata. | +| `userAgent` | `str \| None` | `None` | Browser User-Agent string. | + +## HeyTapMetadata + +| Parameter | Type | Default | Description | +|-----------|------|---------|-------------| +| `apiServer` | `str \| None` | `None` | API server domain without `https://`; required if not `captcha-sec.heytapmobi.com`. | diff --git a/docs/reference/hunt.md b/docs/reference/hunt.md new file mode 100644 index 0000000..e33aa78 --- /dev/null +++ b/docs/reference/hunt.md @@ -0,0 +1,27 @@ +# Hunt + +Solves Hunt captcha challenges, or generates an X-HD value. Proxy is required. + +**API type:** `CustomTask` (with `class: "HUNT"`) + +| Parameter | Type | Default | Description | +|-----------|------|---------|-------------| +| `websiteURL` | `str` | **required** | Full URL of the page with the Hunt captcha. | +| `metadata` | `HuntMetadata` | **required** | Hunt-specific metadata. | +| `userAgent` | `str \| None` | `None` | Browser User-Agent string. | +| `proxy` | `ProxyPayload` | **required** | Proxy settings. | + +## HuntMetadata + +| Parameter | Type | Default | Description | +|-----------|------|---------|-------------| +| `apiGetLib` | `str` | **required** | Full URL of the Hunt `api.js` file. | +| `data` | `str \| None` | `None` | The `meta.token` value returned by the site. | +| `widgetUrl` | `str \| None` | `None` | Full URL of the Hunt widget, including the query string. | + +Pass only `apiGetLib` to generate X-HD. To solve the captcha, add either `data` or `widgetUrl`, never both. + +!!!warning Deprecated +`HuntTask(websiteURL=..., websiteKey=...)` without `metadata` still sends the old `HuntTask` request, emits a +`DeprecationWarning`, and will be removed in 6.0. +!!! diff --git a/docs/reference/image.md b/docs/reference/image.md index b8fc8b0..b05d7c0 100644 --- a/docs/reference/image.md +++ b/docs/reference/image.md @@ -56,4 +56,11 @@ Solves complex image recognition tasks (rotate, match, etc.). | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `imagesBase64` | `list[str]` | **required** | List of base64-encoded images. | -| `task` | `Literal["oocl_rotate_new", "oocl_rotate_double_new", "betpunch_3x3_rotate", "bls", "shein"]` | **required** | Type of recognition task. | +| `task` | `str` | **required** | One of `oocl_rotate_new`, `oocl_rotate_double_new`, `betpunch_3x3_rotate`, `baidu`, `bls_3x3`, `shein`, `bills_audio`, `dli`, `MathSum`, `portugal_text_find_icon`. | +| `taskArgument` | `str \| None` | `None` | Sent as `TaskArgument`. **Required** for `bls_3x3` (the number to find) and `portugal_text_find_icon` (the instruction text). | + +`bills_audio` sends `PayloadType: "Audio"` automatically; pass the audio as base64 in `imagesBase64`. + +!!!warning +`task="bls"` is deprecated: it is still sent as `bls`, with a `DeprecationWarning`, and will be removed in 6.0. Use `bls_3x3` with `taskArgument`. +!!! diff --git a/docs/reference/imperva.md b/docs/reference/imperva.md index 4e921a7..9b34ac1 100644 --- a/docs/reference/imperva.md +++ b/docs/reference/imperva.md @@ -9,11 +9,16 @@ Solves Imperva (Incapsula) challenges. | `websiteURL` | `str` | **required** | URL of the target website. | | `metadata` | `ImpervaTaskMetadata` | **required** | Imperva-specific metadata. | | `userAgent` | `str \| None` | `None` | Browser User-Agent string. | +| `proxy` | `ProxyPayload \| None` | `None` | Proxy settings. Required by the API; a `UserWarning` is emitted without it. | ## ImpervaTaskMetadata | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `incapsulaScriptUrl` | `str` | **required** | Name/URL of the Incapsula JS file. | -| `incapsulaCookie` | `str` | **required** | Cookies from Incapsula (via `document.cookie`). | +| `incapsulaCookies` | `str` | **required** | Cookies from Incapsula (via `document.cookie`). | | `reese84UrlEndpoint` | `str \| None` | `None` | Endpoint where reese84 fingerprint is sent (ends with `?d=site.com`). | + +!!!warning +`incapsulaCookie` (without the trailing `s`) is deprecated: it is still accepted and sent as `incapsulaCookies`, with a `DeprecationWarning`. It will be removed in 6.0. +!!! diff --git a/docs/reference/overview.md b/docs/reference/overview.md index 3b52cf9..21771a6 100644 --- a/docs/reference/overview.md +++ b/docs/reference/overview.md @@ -26,7 +26,15 @@ structures. All classes include: --- -## What's New +## What's New in 5.1 + +- **6 new task types** — Alibaba, Friendly Captcha, FengkongCloud, ARCaptcha, HeyTap, Proton +- **Task cost** — `solve_detailed()` and the other `*_detailed` methods return a `TaskResult` with the task's `cost` +- **New fields** — `minScore` for reCAPTCHA v2 Enterprise, TenDI `metadata`, DataDome `datadomeVersion`, Turnstile `pageData`, image recognition `taskArgument` and new tasks +- **Fixes** — `HuntTask` uses the current `CustomTask`/`HUNT` request; Imperva sends `incapsulaCookies`; image recognition adds `bls_3x3` with `taskArgument` +- **Deprecated** (warning now, removed in 6.0) — `RecaptchaClickTask`, `TemuTask`, `CastleTask`, `HuntTask(websiteKey=...)`, `ImpervaTaskMetadata(incapsulaCookie=...)`, `ComplexImageRecognitionTask(task="bls")` + +## What's New in 5.0 - **Context manager** — use `with` / `async with` to auto-close HTTP connections - **`solve()` / `solve_async()`** — convenience method combining `create_task` + `join_task_result` diff --git a/docs/reference/proton.md b/docs/reference/proton.md new file mode 100644 index 0000000..6db1eb6 --- /dev/null +++ b/docs/reference/proton.md @@ -0,0 +1,19 @@ +# Proton Captcha [!badge text="NEW" variant="success"] + +Solves Proton Captcha challenges. Proxy is required. + +**API type:** `CustomTask` (with `class: "proton"`) + +| Parameter | Type | Default | Description | +|-----------|------|---------|-------------| +| `websiteURL` | `str` | **required** | Address of the main page with the captcha. | +| `metadata` | `ProtonMetadata` | **required** | Proton-specific metadata. | +| `userAgent` | `str \| None` | `None` | Browser User-Agent string. | +| `proxy` | `ProxyPayload` | **required** | Proxy settings. | + +## ProtonMetadata + +| Parameter | Type | Default | Description | +|-----------|------|---------|-------------| +| `HumanVerificationToken` | `str` | **required** | Token from the site's response. | +| `pageAction` | `Literal["login", "signup"]` | **required** | Action on the site. | diff --git a/docs/reference/recaptcha.md b/docs/reference/recaptcha.md index 51fe213..37aa004 100644 --- a/docs/reference/recaptcha.md +++ b/docs/reference/recaptcha.md @@ -34,6 +34,7 @@ Solves Google reCAPTCHA V2 Enterprise challenges. | `pageAction` | `str \| None` | `None` | Action parameter if different from default `"verify"`. | | `enterprisePayload` | `str \| None` | `None` | Additional parameters passed to `grecaptcha.enterprise.render`. | | `apiDomain` | `str \| None` | `None` | Custom domain for loading reCAPTCHA Enterprise. | +| `minScore` | `float \| None` | `None` | Minimum acceptable score, from `0.1` to `0.9`. | | `cookies` | `str \| None` | `None` | Cookies to send with the request. | | `nocache` | `bool \| None` | `None` | Set to `True` to force fresh token generation (prevents reuse of cached tokens). | | `userAgent` | `str \| None` | `None` | Browser User-Agent string. | diff --git a/docs/reference/temu.md b/docs/reference/temu.md index 7396765..b8e431c 100644 --- a/docs/reference/temu.md +++ b/docs/reference/temu.md @@ -1,5 +1,9 @@ # Temu +!!!warning Deprecated +`TemuTask` emits a `DeprecationWarning` and will be removed in 6.0: Temu is no longer in the CapMonster Cloud docs. +!!! + Solves CAPTCHA challenges on Temu using extracted cookies. **API type:** `CustomTask` (with `class: "Temu"`) diff --git a/docs/reference/tendi.md b/docs/reference/tendi.md index f1bd1d0..da0ca2b 100644 --- a/docs/reference/tendi.md +++ b/docs/reference/tendi.md @@ -9,4 +9,12 @@ Solves TenDI-based captcha challenges. | `websiteURL` | `str` | **required** | Address of the page with the captcha. | | `websiteKey` | `str` | **required** | captchaAppId — unique parameter for your site. | | `userAgent` | `str \| None` | `None` | Browser User-Agent string. | -| `proxy` | `ProxyPayload` | **required** | Proxy settings. | +| `metadata` | `TenDIMetadata \| None` | `None` | Optional TenDI-specific metadata. | +| `proxy` | `ProxyPayload \| None` | `None` | Proxy settings. | + +## TenDIMetadata [!badge text="NEW" variant="success"] + +| Parameter | Type | Default | Description | +|-----------|------|---------|-------------| +| `captchaUrl` | `str \| None` | `None` | Link to the captcha script, if the site loads it from a custom domain. | +| `aidEncrypted` | `str \| None` | `None` | Single-use encrypted Aid value issued by the site, if it uses one. | diff --git a/docs/reference/turnstile.md b/docs/reference/turnstile.md index b589dd4..3973a3b 100644 --- a/docs/reference/turnstile.md +++ b/docs/reference/turnstile.md @@ -29,15 +29,16 @@ Solves Cloudflare challenges that return either a token or a `cf_clearance` cook | `websiteKey` | `str` | **required** | Turnstile site key. | | `cloudflareTaskType` | `Literal["token", "cf_clearance"]` | `"token"` | Cloudflare challenge type. | | `userAgent` | `str` | **required** | Browser User-Agent string (must be from Windows OS). | -| `apiJsUrl` | `str \| None` | `None` | Captcha script URL. **Required** for `token` type. | +| `apiJsUrl` | `str \| None` | `None` | Captcha script URL (`token` type only). | +| `pageData` | `str \| None` | `None` | Value of `chlPageData` (`token` type only). | | `htmlPageBase64` | `str \| None` | `None` | Base64-encoded HTML page. **Required** for `cf_clearance` type. | -| `proxy` | `ProxyPayload \| None` | `None` | Proxy settings. **Required** for `cf_clearance`, must be omitted for `token`. | +| `proxy` | `ProxyPayload \| None` | `None` | Proxy settings. **Required** for `cf_clearance`, optional for `token`. | | `pageAction` | `str \| None` | `None` | Action field from the captcha callback function. | | `data` | `str \| None` | `None` | Value of the `cData` parameter. | ### Validation rules -- **`token` type:** `apiJsUrl` is required; `proxy` must be omitted. +- **`token` type:** no extra requirement; pass `pageAction`, `data` and `pageData` from the challenge page. - **`cf_clearance` type:** `htmlPageBase64` and `proxy` are both required. --- diff --git a/src/capmonster_python/__init__.py b/src/capmonster_python/__init__.py index 7a339d4..e3210bf 100644 --- a/src/capmonster_python/__init__.py +++ b/src/capmonster_python/__init__.py @@ -1,15 +1,20 @@ from .client import CapmonsterClient +from .methods import TaskResult from .exceptions import * from .tasks import * __all__ = [ "CapmonsterClient", + "TaskResult", "VanillaTaskPayload", "ProxyPayload", "UserAgentPayload", + "AlibabaTask", + "AlibabaMetadata", "AltchaTask", "AltchaMetadata", "AmazonTask", + "ARCaptchaTask", "BasiliskTask", "BinanceTask", "CastleTask", @@ -19,15 +24,24 @@ "ComplexImageRecognitionTask", "DataDomeTask", "DataDomeMetadata", + "FengkongCloudTask", + "FengkongCloudMetadata", + "FriendlyTask", + "FriendlyMetadata", "FunCaptchaTask", "GeeTestV3Task", "GeeTestV4Task", + "HeyTapTask", + "HeyTapMetadata", "HuntTask", + "HuntMetadata", "ImageToTextTask", "ImpervaTask", "ImpervaTaskMetadata", "MTCaptchaTask", "ProsopoTask", + "ProtonTask", + "ProtonMetadata", "RecaptchaClickTask", "RecaptchaV2Task", "RecaptchaV2EnterpriseTask", @@ -35,6 +49,7 @@ "RecaptchaV3EnterpriseTask", "TemuTask", "TenDITask", + "TenDIMetadata", "TSPDTask", "TSPDMetadata", "TurnstileTask", diff --git a/src/capmonster_python/_deprecation.py b/src/capmonster_python/_deprecation.py new file mode 100644 index 0000000..21e58dd --- /dev/null +++ b/src/capmonster_python/_deprecation.py @@ -0,0 +1,24 @@ +import warnings + + +def warn_deprecated(message: str, stacklevel: int = 3) -> None: + """ + Emits a DeprecationWarning pointing at the caller's code. + + Args: + message: What is deprecated and what to use instead. + stacklevel: How many frames up the warning should point to. + """ + warnings.warn(message, DeprecationWarning, stacklevel=stacklevel) + + +def warn_proxy_required(task: str, stacklevel: int = 3) -> None: + """ + Emits a UserWarning when a task that the API documents as proxy-only is created without a proxy. + + Args: + task: Name of the task class. + stacklevel: How many frames up the warning should point to. + """ + warnings.warn(f"{task}: CapMonster Cloud requires your own proxy for this task; " + f"the request will likely be rejected without one.", UserWarning, stacklevel=stacklevel) diff --git a/src/capmonster_python/client.py b/src/capmonster_python/client.py index 6694eee..246966b 100644 --- a/src/capmonster_python/client.py +++ b/src/capmonster_python/client.py @@ -5,7 +5,8 @@ from httpx import Response, AsyncClient, Client from .exceptions import CapmonsterAPIException, CapmonsterException -from .methods import GetBalancePayload, GetTaskResultPayload, CreateTaskPayload, ReportIncorrectCaptchaPayload +from .methods import GetBalancePayload, GetTaskResultPayload, CreateTaskPayload, ReportIncorrectCaptchaPayload, \ + TaskResult from .tasks.task import TaskPayload @@ -140,9 +141,22 @@ def get_task_result(self, task_id: int) -> dict: result API endpoint. If the solution is not found in the response, an empty dictionary is returned. """ + return self.get_task_result_detailed(task_id).solution + + def get_task_result_detailed(self, task_id: int) -> TaskResult: + """ + Fetches the full result of a specific task by its identifier, including its status and cost. + + Args: + task_id (int): An integer representing the unique identifier of the task. + + Returns: + TaskResult: The status, solution and cost of the task. The solution is an empty + dictionary and the cost is None while the task is processing. + """ payload = GetTaskResultPayload(clientKey=self.api_key, taskId=task_id).model_dump() response = self.__make_sync_request(self.__TASK_RESULT_URL, payload).json() - return response.get("solution", {}) + return TaskResult.from_response(response) async def get_task_result_async(self, task_id: int) -> dict: """ @@ -162,10 +176,22 @@ async def get_task_result_async(self, task_id: int) -> dict: result API endpoint. If the solution is not found in the response, an empty dictionary is returned. """ + return (await self.get_task_result_detailed_async(task_id)).solution + + async def get_task_result_detailed_async(self, task_id: int) -> TaskResult: + """ + Asynchronously fetches the full result of a specific task by its identifier, including its status and cost. + + Args: + task_id (int): An integer representing the unique identifier of the task. + + Returns: + TaskResult: The status, solution and cost of the task. The solution is an empty + dictionary and the cost is None while the task is processing. + """ payload = GetTaskResultPayload(clientKey=self.api_key, taskId=task_id).model_dump() request = await self.__make_async_request(self.__TASK_RESULT_URL, payload) - response = request.json() - return response.get("solution", {}) + return TaskResult.from_response(request.json()) def join_task_result(self, task_id: int) -> dict: """ @@ -179,16 +205,31 @@ def join_task_result(self, task_id: int) -> dict: dict: The result of the task if successfully retrieved within the maximum retries. + Raises: + CapmonsterException: + If the maximum retry limit is exceeded without obtaining the task result. + """ + return self.join_task_result_detailed(task_id).solution + + def join_task_result_detailed(self, task_id: int) -> TaskResult: + """ + Polls the result of a task like `join_task_result`, but returns its status and cost too. + + Args: + task_id: The identifier of the task for which the result needs to be retrieved. + + Returns: + TaskResult: The status, solution and cost of the completed task. + Raises: CapmonsterException: If the maximum retry limit is exceeded without obtaining the task result. """ for _ in range(0, self.__max_retries + 1): - result = self.get_task_result(task_id) - if result: + result = self.get_task_result_detailed(task_id) + if result.solution: return result - elif not result: - sleep(self.__retry_delay) + sleep(self.__retry_delay) raise CapmonsterAPIException( 61, "ERROR_MAXIMUM_TIME_EXCEED", "Maximum time is exceed.") @@ -204,16 +245,31 @@ async def join_task_result_async(self, task_id: int) -> dict: dict: The result of the task if successfully retrieved within the maximum retries. + Raises: + CapmonsterException: + If the maximum retry limit is exceeded without obtaining the task result. + """ + return (await self.join_task_result_detailed_async(task_id)).solution + + async def join_task_result_detailed_async(self, task_id: int) -> TaskResult: + """ + Asynchronously polls the result of a task like `join_task_result_async`, but returns its status and cost too. + + Args: + task_id: The identifier of the task for which the result needs to be retrieved. + + Returns: + TaskResult: The status, solution and cost of the completed task. + Raises: CapmonsterException: If the maximum retry limit is exceeded without obtaining the task result. """ for _ in range(0, self.__max_retries + 1): - result = await self.get_task_result_async(task_id) - if result: + result = await self.get_task_result_detailed_async(task_id) + if result.solution: return result - elif not result: - await asyncio.sleep(self.__retry_delay) + await asyncio.sleep(self.__retry_delay) raise CapmonsterAPIException( 61, "ERROR_MAXIMUM_TIME_EXCEED", "Maximum time is exceed.") @@ -230,8 +286,21 @@ def solve(self, task: TaskPayload, callback_url: Optional[str] = None) -> dict: Returns: dict: The solution dictionary from the completed task. """ + return self.solve_detailed(task, callback_url).solution + + def solve_detailed(self, task: TaskPayload, callback_url: Optional[str] = None) -> TaskResult: + """ + Creates a task and polls for its result like `solve`, but returns its status and cost too. + + Args: + task: The task configuration payload. + callback_url: An optional callback URL for task completion. + + Returns: + TaskResult: The status, solution and cost of the completed task. + """ task_id = self.create_task(task, callback_url) - return self.join_task_result(task_id) + return self.join_task_result_detailed(task_id) async def solve_async(self, task: TaskPayload, callback_url: Optional[str] = None) -> dict: """ @@ -246,8 +315,21 @@ async def solve_async(self, task: TaskPayload, callback_url: Optional[str] = Non Returns: dict: The solution dictionary from the completed task. """ + return (await self.solve_detailed_async(task, callback_url)).solution + + async def solve_detailed_async(self, task: TaskPayload, callback_url: Optional[str] = None) -> TaskResult: + """ + Async version of `solve_detailed`: creates a task and polls for its result, including its status and cost. + + Args: + task: The task configuration payload. + callback_url: An optional callback URL for task completion. + + Returns: + TaskResult: The status, solution and cost of the completed task. + """ task_id = await self.create_task_async(task, callback_url) - return await self.join_task_result_async(task_id) + return await self.join_task_result_detailed_async(task_id) def report_incorrect_image(self, task_id: int) -> None: """ diff --git a/src/capmonster_python/methods.py b/src/capmonster_python/methods.py index 94d5364..455c603 100644 --- a/src/capmonster_python/methods.py +++ b/src/capmonster_python/methods.py @@ -35,3 +35,23 @@ class CreateTaskPayload(BaseModel): @field_serializer("task") def serialize_task(self, task: TaskPayload, _info) -> dict: return task.to_request() + + +class TaskResult(BaseModel): + """ + Represents the full result of a task returned by getTaskResult. + + Attributes: + status (str): "processing" while the task is being solved, "ready" when it is done. + solution (dict): The solution of the task; empty while the task is processing. + cost (Optional[float]): Cost of the task in USD; only returned when the task is ready. + """ + status: str = Field(default="processing", description="Task status: processing or ready.") + solution: dict = Field(default_factory=dict, description="Task solution.") + cost: Optional[float] = Field(default=None, description="Cost of the task in USD.") + + @classmethod + def from_response(cls, response: dict) -> "TaskResult": + return cls(status=response.get("status") or "processing", + solution=response.get("solution") or {}, + cost=response.get("cost")) diff --git a/src/capmonster_python/tasks/__init__.py b/src/capmonster_python/tasks/__init__.py index 4a71aa9..7ed3e48 100644 --- a/src/capmonster_python/tasks/__init__.py +++ b/src/capmonster_python/tasks/__init__.py @@ -1,18 +1,24 @@ +from .alibaba import AlibabaTask, AlibabaMetadata from .altcha import AltchaTask, AltchaMetadata from .amazon import AmazonTask +from .arcaptcha import ARCaptchaTask from .basilisk import BasiliskTask from .binance import BinanceTask from .castle import CastleTask, CastleMetadata from .complex_image_recaptcha import ComplexImageRecaptchaTask, ComplexImageRecaptchaMetadata from .complex_image_recognition import ComplexImageRecognitionTask from .datadome import DataDomeTask, DataDomeMetadata +from .fengkongcloud import FengkongCloudTask, FengkongCloudMetadata +from .friendly import FriendlyTask, FriendlyMetadata from .funcaptcha import FunCaptchaTask from .geetest import GeeTestV4Task, GeeTestV3Task -from .hunt import HuntTask +from .heytap import HeyTapTask, HeyTapMetadata +from .hunt import HuntTask, HuntMetadata from .image_to_text import ImageToTextTask from .imperva import ImpervaTask, ImpervaTaskMetadata from .mtcaptcha import MTCaptchaTask from .prosopo import ProsopoTask +from .proton import ProtonTask, ProtonMetadata from .recaptcha_click import RecaptchaClickTask from .recaptcha_v2 import RecaptchaV2Task from .recaptcha_v2_enterprise import RecaptchaV2EnterpriseTask @@ -20,7 +26,7 @@ from .recaptcha_v3_enterprise import RecaptchaV3EnterpriseTask from .task import VanillaTaskPayload, ProxyPayload, UserAgentPayload from .temu import TemuTask -from .tendi import TenDITask +from .tendi import TenDITask, TenDIMetadata from .tspd import TSPDTask, TSPDMetadata from .turnstile import TurnstileTask, TurnstileCloudFlareTask, TurnstileWaitingRoomTask from .yidun import YidunTask @@ -29,9 +35,12 @@ "VanillaTaskPayload", "ProxyPayload", "UserAgentPayload", + "AlibabaTask", + "AlibabaMetadata", "AltchaTask", "AltchaMetadata", "AmazonTask", + "ARCaptchaTask", "BasiliskTask", "BinanceTask", "CastleTask", @@ -41,15 +50,24 @@ "ComplexImageRecognitionTask", "DataDomeTask", "DataDomeMetadata", + "FengkongCloudTask", + "FengkongCloudMetadata", + "FriendlyTask", + "FriendlyMetadata", "FunCaptchaTask", "GeeTestV3Task", "GeeTestV4Task", + "HeyTapTask", + "HeyTapMetadata", "HuntTask", + "HuntMetadata", "ImageToTextTask", "ImpervaTask", "ImpervaTaskMetadata", "MTCaptchaTask", "ProsopoTask", + "ProtonTask", + "ProtonMetadata", "RecaptchaClickTask", "RecaptchaV2Task", "RecaptchaV2EnterpriseTask", @@ -57,6 +75,7 @@ "RecaptchaV3EnterpriseTask", "TemuTask", "TenDITask", + "TenDIMetadata", "TSPDTask", "TSPDMetadata", "TurnstileTask", diff --git a/src/capmonster_python/tasks/alibaba.py b/src/capmonster_python/tasks/alibaba.py new file mode 100644 index 0000000..8e7c508 --- /dev/null +++ b/src/capmonster_python/tasks/alibaba.py @@ -0,0 +1,69 @@ +from typing import Any, Optional + +from pydantic import Field, BaseModel, model_validator + +from .task import TaskPayload, ProxyPayload, UserAgentPayload +from ..exceptions import CapmonsterValidationException + + +class AlibabaMetadata(BaseModel): + """ + Metadata for Alibaba task. + + `sceneId` and `prefix` are required unless `punishUrl` is given. Pass the other + fields only if the website uses them. + + Attributes: + sceneId: The captcha scenario identifier. + prefix: Captcha initialization parameter (the subdomain of the captcha-open URL). + userId: Unique identifier of the user or session on the website side. + userUserId: Additional (secondary) user identifier. + verifyType: Version or type of the verification mechanism, e.g. "1.0". + region: Region that processes the captcha, e.g. "cn" or "sgp". + UserCertifyId: Verification ID of the current captcha session. + apiGetLib: Link to the captcha JS library used by the website. + punishUrl: Full URL of the /punish verification page, including its query string. + cookieRequired: Return cookies with the solution (for Alibaba WAF). + """ + sceneId: Optional[str] = Field(default=None, description="The captcha scenario identifier.") + prefix: Optional[str] = Field(default=None, description="Captcha initialization parameter.") + userId: Optional[str] = Field(default=None, description="User or session identifier.") + userUserId: Optional[str] = Field(default=None, description="Secondary user identifier.") + verifyType: Optional[str] = Field(default=None, description="Verification mechanism version.") + region: Optional[str] = Field(default=None, description="Region that processes the captcha.") + UserCertifyId: Optional[str] = Field(default=None, description="Verification ID of the captcha session.") + apiGetLib: Optional[str] = Field(default=None, description="Link to the captcha JS library.") + punishUrl: Optional[str] = Field(default=None, description="Full URL of the /punish verification page.") + cookieRequired: Optional[bool] = Field(default=None, description="Return cookies with the solution.") + + @model_validator(mode="after") + def check_required(self) -> "AlibabaMetadata": + if self.punishUrl is None and (self.sceneId is None or self.prefix is None): + raise CapmonsterValidationException("sceneId and prefix are required unless punishUrl is set", + task="AlibabaTask") + return self + + +class AlibabaTask(TaskPayload, UserAgentPayload): + """ + Represents a task for solving Alibaba captcha challenges. + + Uses CustomTask type with class "alibaba". + + Attributes: + websiteURL: Full URL of the page with the captcha. + metadata: Alibaba-specific metadata. + proxy: Optional proxy settings. + """ + type: str = Field(default="CustomTask", frozen=True) + class_: str = Field(default="alibaba", alias="class", frozen=True) + websiteURL: str = Field(..., description='Full URL of the page with the captcha.') + metadata: AlibabaMetadata = Field(..., description='Alibaba-specific metadata.') + proxy: Optional[ProxyPayload] = Field(default=None, description='Proxy settings.') + + def to_request(self) -> dict[str, Any]: + base = self.model_dump(exclude_none=True, by_alias=True) + proxy_dict = base.pop("proxy", {}) + if proxy_dict: + base.update(proxy_dict) + return base diff --git a/src/capmonster_python/tasks/arcaptcha.py b/src/capmonster_python/tasks/arcaptcha.py new file mode 100644 index 0000000..761e75b --- /dev/null +++ b/src/capmonster_python/tasks/arcaptcha.py @@ -0,0 +1,23 @@ +from typing import Any, Optional + +from pydantic import Field + +from .task import TaskPayload, UserAgentPayload + + +class ARCaptchaTask(TaskPayload, UserAgentPayload): + """ + Represents a task for solving ARCaptcha challenges. This task does not use a proxy. + + Attributes: + websiteURL: Address of the main page where the captcha is located. + websiteKey: The siteKey value found on the page. + isInvisible: Set to True if the captcha is invisible. + """ + type: str = Field(default="ArCaptchaTask", frozen=True) + websiteURL: str = Field(..., description='Address of the main page where the captcha is located.') + websiteKey: str = Field(..., description='The siteKey value found on the page.') + isInvisible: Optional[bool] = Field(default=None, description='Set to true if the captcha is invisible.') + + def to_request(self) -> dict[str, Any]: + return self.model_dump(exclude_none=True) diff --git a/src/capmonster_python/tasks/castle.py b/src/capmonster_python/tasks/castle.py index 1ab3124..ded580c 100644 --- a/src/capmonster_python/tasks/castle.py +++ b/src/capmonster_python/tasks/castle.py @@ -3,6 +3,7 @@ from pydantic import Field, BaseModel from .task import TaskPayload, ProxyPayload, UserAgentPayload +from .._deprecation import warn_deprecated class CastleMetadata(BaseModel): @@ -21,6 +22,8 @@ class CastleMetadata(BaseModel): class CastleTask(TaskPayload, UserAgentPayload): """ + Deprecated: will be removed in 6.0. + Represents a task for solving Castle challenges. Uses CustomTask type with class "Castle". @@ -38,6 +41,10 @@ class CastleTask(TaskPayload, UserAgentPayload): metadata: CastleMetadata = Field(..., description='Castle-specific metadata.') proxy: Optional[ProxyPayload] = Field(default=None, description='Proxy settings.') + def model_post_init(self, __context: Any) -> None: + warn_deprecated("CastleTask is deprecated and will be removed in 6.0: " + "Castle is no longer in the CapMonster Cloud docs.", stacklevel=4) + def to_request(self) -> dict[str, Any]: base = self.model_dump(exclude_none=True, by_alias=True) proxy_dict = base.pop("proxy", {}) diff --git a/src/capmonster_python/tasks/complex_image_recognition.py b/src/capmonster_python/tasks/complex_image_recognition.py index c6027e9..f3cc63c 100644 --- a/src/capmonster_python/tasks/complex_image_recognition.py +++ b/src/capmonster_python/tasks/complex_image_recognition.py @@ -1,8 +1,12 @@ -from typing import List, Literal, Any +from typing import Any, List, Literal, Optional -from pydantic import Field +from pydantic import Field, model_validator from .task import TaskPayload +from .._deprecation import warn_deprecated +from ..exceptions import CapmonsterValidationException + +TASKS_WITH_ARGUMENT = ("bls_3x3", "portugal_text_find_icon") class ComplexImageRecognitionTask(TaskPayload): @@ -13,21 +17,41 @@ class ComplexImageRecognitionTask(TaskPayload): imagesBase64: List of base64 encoded images. This is required and contains raw image data in base64 format. task: A string indicating one of the predefined types of recognition - task. This must be one of "oocl_rotate_new", "oocl_rotate_double_new", - "betpunch_3x3_rotate", "bls", "shein". + task: "oocl_rotate_new", "oocl_rotate_double_new", "betpunch_3x3_rotate", + "baidu", "bls_3x3", "shein", "bills_audio", "dli", "MathSum" or + "portugal_text_find_icon". "bls" is deprecated: it is still sent as "bls", with a warning. + taskArgument: Extra task input sent as metadata "TaskArgument"; required for + "bls_3x3" (the number to find) and "portugal_text_find_icon" (the instruction text). """ type: str = Field(default="ComplexImageTask", frozen=True) class_: str = Field(default="recognition", alias="class", frozen=True) imagesBase64: List[str] = Field(..., description="List of base64 encoded images.") - task: Literal["oocl_rotate_new", "oocl_rotate_double_new", "betpunch_3x3_rotate", "bls", "shein"] = Field(..., - description="Type of task.") + task: Literal["oocl_rotate_new", "oocl_rotate_double_new", "betpunch_3x3_rotate", "baidu", "bls_3x3", "bls", + "shein", "bills_audio", "dli", "MathSum", "portugal_text_find_icon"] = Field(..., + description="Type of task.") + taskArgument: Optional[str] = Field(default=None, description="Extra task input, sent as TaskArgument.") + + @model_validator(mode="after") + def check_task(self) -> "ComplexImageRecognitionTask": + if self.task == "bls": + warn_deprecated("ComplexImageRecognitionTask(task='bls') is deprecated and will be removed in 6.0; " + "use task='bls_3x3' with taskArgument.", stacklevel=4) + elif self.task in TASKS_WITH_ARGUMENT and self.taskArgument is None: + raise CapmonsterValidationException(f"taskArgument is required for task '{self.task}'", + field="taskArgument", task="ComplexImageRecognitionTask") + return self def to_request(self) -> dict[str, Any]: base = self.model_dump(exclude_none=True, by_alias=True) task = base.pop("task") + task_argument = base.pop("taskArgument", None) if "metadata" not in base: base["metadata"] = {} base["metadata"]["Task"] = task + if task_argument is not None: + base["metadata"]["TaskArgument"] = task_argument + if task == "bills_audio": + base["metadata"]["PayloadType"] = "Audio" return base diff --git a/src/capmonster_python/tasks/datadome.py b/src/capmonster_python/tasks/datadome.py index 6ae13b0..2985795 100644 --- a/src/capmonster_python/tasks/datadome.py +++ b/src/capmonster_python/tasks/datadome.py @@ -3,6 +3,7 @@ from pydantic import Field, BaseModel, model_validator from .task import TaskPayload, UserAgentPayload, ProxyPayload +from .._deprecation import warn_proxy_required from ..exceptions import CapmonsterValidationException @@ -17,6 +18,7 @@ class DataDomeMetadata(BaseModel): like: "https://geo.captcha-delivery.com/captcha/?initialCid=...". datadomeCookie: Mandatory; Stores the DataDome cookies, retrievable on the page using `document.cookie`. + datadomeVersion: Optional; DataDome script version, if the site requires it. Raises: CapmonsterValidationException: If neither `htmlPageBase64` nor `captchaUrl` is provided, @@ -28,6 +30,8 @@ class DataDomeMetadata(BaseModel): description="\"captchaUrl\" - link to the captcha. Usually it looks like this: \"https://geo.captcha-delivery.com/captcha/?initialCid=...\"") datadomeCookie: str = Field(..., description="Your cookies from datadome. You can get it on the page using document.cookie") + datadomeVersion: Optional[str] = Field(default=None, + description="DataDome script version, if the site requires it.") @model_validator(mode="after") def validate_fields(self) -> "DataDomeMetadata": @@ -54,6 +58,10 @@ class DataDomeTask(TaskPayload, UserAgentPayload): proxy: Optional[ProxyPayload] = Field(default=None, description="Proxy settings.") metadata: DataDomeMetadata = Field(default=None, description="Additional data about the captcha.") + def model_post_init(self, __context: Any) -> None: + if self.proxy is None: + warn_proxy_required("DataDomeTask", stacklevel=4) + def to_request(self) -> dict[str, Any]: base = self.model_dump(exclude_none=True, by_alias=True) proxy_dict = base.pop("proxy", {}) diff --git a/src/capmonster_python/tasks/fengkongcloud.py b/src/capmonster_python/tasks/fengkongcloud.py new file mode 100644 index 0000000..c4b71b7 --- /dev/null +++ b/src/capmonster_python/tasks/fengkongcloud.py @@ -0,0 +1,39 @@ +from typing import Any, Optional + +from pydantic import Field, BaseModel + +from .task import TaskPayload, UserAgentPayload + + +class FengkongCloudMetadata(BaseModel): + """ + Optional metadata for FengkongCloud task. + + Attributes: + apiJsUrl: Link to smcp.min.js, e.g. "https://castatic.fengkongcloud.com/pr/vX.X.X/smcp.min.js". + """ + apiJsUrl: Optional[str] = Field(default=None, description='Link to smcp.min.js.') + + +class FengkongCloudTask(TaskPayload, UserAgentPayload): + """ + Represents a task for solving FengkongCloud captcha challenges. + + Uses CustomTask type with class "fengkongcloud". This task does not use a proxy. + + Attributes: + websiteURL: Address of the main page where the captcha is located. + websiteKey: The siteKey value found on the page. + metadata: Optional FengkongCloud-specific metadata (apiJsUrl). + """ + type: str = Field(default="CustomTask", frozen=True) + class_: str = Field(default="fengkongcloud", alias="class", frozen=True) + websiteURL: str = Field(..., description='Address of the main page where the captcha is located.') + websiteKey: str = Field(..., description='The siteKey value found on the page.') + metadata: Optional[FengkongCloudMetadata] = Field(default=None, description='FengkongCloud-specific metadata.') + + def to_request(self) -> dict[str, Any]: + base = self.model_dump(exclude_none=True, by_alias=True) + if base.get("metadata") == {}: + base.pop("metadata") + return base diff --git a/src/capmonster_python/tasks/friendly.py b/src/capmonster_python/tasks/friendly.py new file mode 100644 index 0000000..343c351 --- /dev/null +++ b/src/capmonster_python/tasks/friendly.py @@ -0,0 +1,43 @@ +from typing import Any, Optional + +from pydantic import Field, BaseModel + +from .task import TaskPayload, ProxyPayload, UserAgentPayload + + +class FriendlyMetadata(BaseModel): + """ + Metadata for Friendly Captcha task. + + Attributes: + apiGetLib: URL of the widget JS file: for V1 the friendly-challenge widget.module.min.js, + for V2 the site.min.js loaded on the page. + """ + apiGetLib: str = Field(..., description='URL of the Friendly Captcha widget JS file.') + + +class FriendlyTask(TaskPayload, UserAgentPayload): + """ + Represents a task for solving Friendly Captcha challenges. + + Uses CustomTask type with class "friendly". + + Attributes: + websiteURL: Full URL of the page with the captcha. + websiteKey: Friendly Captcha site key. + metadata: Friendly-specific metadata (apiGetLib). + proxy: Optional proxy settings. + """ + type: str = Field(default="CustomTask", frozen=True) + class_: str = Field(default="friendly", alias="class", frozen=True) + websiteURL: str = Field(..., description='Full URL of the page with the captcha.') + websiteKey: str = Field(..., description='Friendly Captcha site key.') + metadata: FriendlyMetadata = Field(..., description='Friendly-specific metadata.') + proxy: Optional[ProxyPayload] = Field(default=None, description='Proxy settings.') + + def to_request(self) -> dict[str, Any]: + base = self.model_dump(exclude_none=True, by_alias=True) + proxy_dict = base.pop("proxy", {}) + if proxy_dict: + base.update(proxy_dict) + return base diff --git a/src/capmonster_python/tasks/funcaptcha.py b/src/capmonster_python/tasks/funcaptcha.py index be39ee9..25f8e63 100644 --- a/src/capmonster_python/tasks/funcaptcha.py +++ b/src/capmonster_python/tasks/funcaptcha.py @@ -3,6 +3,7 @@ from pydantic import Field from .task import TaskPayload, ProxyPayload, UserAgentPayload +from .._deprecation import warn_proxy_required class FunCaptchaTask(TaskPayload, UserAgentPayload): @@ -32,6 +33,10 @@ class FunCaptchaTask(TaskPayload, UserAgentPayload): description='Additional cookies in the format: cookieName1=value1; cookieName2=value2.') proxy: Optional[ProxyPayload] = Field(default=None, description='Proxy settings.') + def model_post_init(self, __context: Any) -> None: + if self.proxy is None: + warn_proxy_required("FunCaptchaTask", stacklevel=4) + def to_request(self) -> dict[str, Any]: base = self.model_dump(exclude_none=True) proxy_dict = base.pop("proxy", {}) diff --git a/src/capmonster_python/tasks/heytap.py b/src/capmonster_python/tasks/heytap.py new file mode 100644 index 0000000..6311c79 --- /dev/null +++ b/src/capmonster_python/tasks/heytap.py @@ -0,0 +1,40 @@ +from typing import Any, Optional + +from pydantic import Field, BaseModel + +from .task import TaskPayload, UserAgentPayload + + +class HeyTapMetadata(BaseModel): + """ + Optional metadata for HeyTap task. + + Attributes: + apiServer: HeyTap API server domain without "https://"; required if it differs + from the default "captcha-sec.heytapmobi.com". + """ + apiServer: Optional[str] = Field(default=None, description='HeyTap API server domain without https://.') + + +class HeyTapTask(TaskPayload, UserAgentPayload): + """ + Represents a task for solving HeyTap captcha challenges. + + Uses CustomTask type with class "heytap". This task does not use a proxy. + + Attributes: + websiteURL: Address of the main page where the captcha is located. + websiteKey: The siteKey value found on the page. + metadata: Optional HeyTap-specific metadata (apiServer). + """ + type: str = Field(default="CustomTask", frozen=True) + class_: str = Field(default="heytap", alias="class", frozen=True) + websiteURL: str = Field(..., description='Address of the main page where the captcha is located.') + websiteKey: str = Field(..., description='The siteKey value found on the page.') + metadata: Optional[HeyTapMetadata] = Field(default=None, description='HeyTap-specific metadata.') + + def to_request(self) -> dict[str, Any]: + base = self.model_dump(exclude_none=True, by_alias=True) + if base.get("metadata") == {}: + base.pop("metadata") + return base diff --git a/src/capmonster_python/tasks/hunt.py b/src/capmonster_python/tasks/hunt.py index 0caaccd..f0fb832 100644 --- a/src/capmonster_python/tasks/hunt.py +++ b/src/capmonster_python/tasks/hunt.py @@ -1,26 +1,79 @@ from typing import Optional, Any -from pydantic import Field +from pydantic import Field, BaseModel, model_validator from .task import TaskPayload, ProxyPayload, UserAgentPayload +from .._deprecation import warn_deprecated +from ..exceptions import CapmonsterValidationException + + +class HuntMetadata(BaseModel): + """ + Metadata for Hunt task. + + Pass only `apiGetLib` to generate an X-HD value. To solve the captcha, also pass + either `data` (the `meta.token` returned by the site) or `widgetUrl`, never both. + + Attributes: + apiGetLib: Full URL of the Hunt `api.js` file. + data: The `meta.token` value obtained from the site. + widgetUrl: Full URL of the Hunt captcha widget, including the query string. + """ + apiGetLib: str = Field(..., description='Full URL of the Hunt api.js file.') + data: Optional[str] = Field(default=None, description='The meta.token value obtained from the site.') + widgetUrl: Optional[str] = Field(default=None, description='Full URL of the Hunt captcha widget.') + + @model_validator(mode="after") + def check_data_or_widget(self) -> "HuntMetadata": + if self.data is not None and self.widgetUrl is not None: + raise CapmonsterValidationException("data and widgetUrl must not be used together", + task="HuntTask") + return self class HuntTask(TaskPayload, UserAgentPayload): """ Represents a task for solving Hunt captcha challenges. + Uses CustomTask type with class "HUNT". Proxy is required for this task type. + Attributes: websiteURL: The URL of the webpage containing the captcha. - websiteKey: The Hunt captcha site key. - proxy: Optional proxy settings. + metadata: Hunt-specific metadata (apiGetLib, data or widgetUrl). + proxy: Proxy settings. + websiteKey: Deprecated. Sends the legacy `HuntTask` request; use `metadata` instead. """ - type: str = Field(default="HuntTask", frozen=True) + type: str = Field(default="CustomTask", frozen=True) + class_: str = Field(default="HUNT", alias="class", frozen=True) websiteURL: str = Field(..., description='Address of a webpage with captcha.') - websiteKey: str = Field(..., description='Hunt captcha site key.') + metadata: Optional[HuntMetadata] = Field(default=None, description='Hunt-specific metadata.') + websiteKey: Optional[str] = Field(default=None, description='Deprecated: legacy Hunt site key.') proxy: Optional[ProxyPayload] = Field(default=None, description='Proxy settings.') + @model_validator(mode="before") + @classmethod + def set_legacy_type(cls, data: Any) -> Any: + if isinstance(data, dict) and data.get("metadata") is None and data.get("websiteKey") is not None: + data = {**data, "type": "HuntTask"} + return data + + @model_validator(mode="after") + def check_mode(self) -> "HuntTask": + if self.metadata is None: + if self.websiteKey is None: + raise CapmonsterValidationException("metadata is required", field="metadata", task="HuntTask") + warn_deprecated("HuntTask(websiteKey=...) sends the legacy 'HuntTask' request and will be removed " + "in 6.0; pass metadata=HuntMetadata(apiGetLib=..., ...) and a proxy instead.", + stacklevel=4) + elif self.proxy is None: + raise CapmonsterValidationException("proxy is required", field="proxy", task="HuntTask") + return self + def to_request(self) -> dict[str, Any]: - base = self.model_dump(exclude_none=True) + if self.metadata is None: + base = self.model_dump(exclude_none=True, exclude={"class_", "metadata"}) + else: + base = self.model_dump(exclude_none=True, by_alias=True, exclude={"websiteKey"}) proxy_dict = base.pop("proxy", {}) if proxy_dict: base.update(proxy_dict) diff --git a/src/capmonster_python/tasks/imperva.py b/src/capmonster_python/tasks/imperva.py index 620ad56..b32e71a 100644 --- a/src/capmonster_python/tasks/imperva.py +++ b/src/capmonster_python/tasks/imperva.py @@ -1,8 +1,9 @@ from typing import Optional, Any -from pydantic import Field, BaseModel +from pydantic import Field, BaseModel, model_validator -from .task import TaskPayload, UserAgentPayload +from .task import TaskPayload, UserAgentPayload, ProxyPayload +from .._deprecation import warn_deprecated, warn_proxy_required class ImpervaTaskMetadata(BaseModel): @@ -11,24 +12,45 @@ class ImpervaTaskMetadata(BaseModel): Attributes: incapsulaScriptUrl: Name of the Incapsula JS file. - incapsulaCookie: Your cookies from Incapsula. They can be obtained on the - page using document.cookie. + incapsulaCookies: Your cookies from Incapsula. They can be obtained on the + page using document.cookie. The old `incapsulaCookie` keyword is still + accepted but deprecated. reese84UrlEndpoint: Optional. The name of the endpoint where the reese84 fingerprint is sent, found among the network requests and typically ending with "?d=site.com". """ incapsulaScriptUrl: str = Field(..., description="Name of the Incapsula JS file.") - incapsulaCookie: str = Field(..., - description="Your cookies from Incapsula. They can be obtained on the page using document.cookie") + incapsulaCookies: str = Field(..., + description="Your cookies from Incapsula. They can be obtained on the page using document.cookie") reese84UrlEndpoint: Optional[str] = Field(default=None, description="The name of the endpoint where the reese84 " "fingerprint is sent can be found among the " "requests and ends with ?d=site.com") + @model_validator(mode="before") + @classmethod + def rename_legacy_cookie(cls, data: Any) -> Any: + if isinstance(data, dict) and "incapsulaCookie" in data: + warn_deprecated("ImpervaTaskMetadata(incapsulaCookie=...) is deprecated and will be removed in 6.0; " + "use incapsulaCookies=... instead.", stacklevel=4) + data = dict(data) + legacy = data.pop("incapsulaCookie") + data.setdefault("incapsulaCookies", legacy) + return data + + @property + def incapsulaCookie(self) -> str: + """Deprecated alias of `incapsulaCookies`.""" + warn_deprecated("ImpervaTaskMetadata.incapsulaCookie is deprecated; use incapsulaCookies.") + return self.incapsulaCookies + class ImpervaTask(TaskPayload, UserAgentPayload): """ Represents a task for handling and solving an Imperva-based challenge. + Proxy is required for this task type by CapMonster Cloud; a UserWarning is + emitted when it is missing. + Attributes: type (str): The identifier for the type of task. This attribute is frozen and defaults to "CustomTask". @@ -40,11 +62,22 @@ class ImpervaTask(TaskPayload, UserAgentPayload): metadata (ImpervaTaskMetadata): Encapsulated metadata specific to the Imperva challenge, such as the website key. + + proxy (ProxyPayload): Proxy settings. """ type: str = Field(default="CustomTask", frozen=True) class_: str = Field(default="Imperva", alias="class", frozen=True) websiteURL: str = Field(..., description="URL of the website to be solved.") metadata: ImpervaTaskMetadata = Field(..., description="Website key.") + proxy: Optional[ProxyPayload] = Field(default=None, description="Proxy settings.") + + def model_post_init(self, __context: Any) -> None: + if self.proxy is None: + warn_proxy_required("ImpervaTask", stacklevel=4) def to_request(self) -> dict[str, Any]: - return self.model_dump(exclude_none=True, by_alias=True) + base = self.model_dump(exclude_none=True, by_alias=True) + proxy_dict = base.pop("proxy", {}) + if proxy_dict: + base.update(proxy_dict) + return base diff --git a/src/capmonster_python/tasks/proton.py b/src/capmonster_python/tasks/proton.py new file mode 100644 index 0000000..e3301fd --- /dev/null +++ b/src/capmonster_python/tasks/proton.py @@ -0,0 +1,40 @@ +from typing import Any, Literal + +from pydantic import Field, BaseModel + +from .task import TaskPayload, ProxyPayload, UserAgentPayload + + +class ProtonMetadata(BaseModel): + """ + Metadata for Proton Captcha task. + + Attributes: + HumanVerificationToken: Token from the site's response. + pageAction: Action on the site: "login" or "signup". + """ + HumanVerificationToken: str = Field(..., description='Token from the site response.') + pageAction: Literal["login", "signup"] = Field(..., description='Action on the site: login or signup.') + + +class ProtonTask(TaskPayload, UserAgentPayload): + """ + Represents a task for solving Proton Captcha challenges. + + Uses CustomTask type with class "proton". Proxy is required for this task type. + + Attributes: + websiteURL: Address of the main page where the captcha is located. + metadata: Proton-specific metadata (HumanVerificationToken, pageAction). + proxy: Proxy settings. + """ + type: str = Field(default="CustomTask", frozen=True) + class_: str = Field(default="proton", alias="class", frozen=True) + websiteURL: str = Field(..., description='Address of the main page where the captcha is located.') + metadata: ProtonMetadata = Field(..., description='Proton-specific metadata.') + proxy: ProxyPayload = Field(..., description='Proxy settings.') + + def to_request(self) -> dict[str, Any]: + base = self.model_dump(exclude_none=True, by_alias=True) + base.update(base.pop("proxy")) + return base diff --git a/src/capmonster_python/tasks/recaptcha_click.py b/src/capmonster_python/tasks/recaptcha_click.py index bc13eec..23582f5 100644 --- a/src/capmonster_python/tasks/recaptcha_click.py +++ b/src/capmonster_python/tasks/recaptcha_click.py @@ -3,10 +3,13 @@ from pydantic import Field from .task import TaskPayload, ProxyPayload, UserAgentPayload +from .._deprecation import warn_deprecated class RecaptchaClickTask(TaskPayload, UserAgentPayload): """ + Deprecated: will be removed in 6.0. + Represents a task for solving click-based reCAPTCHA challenges. Attributes: @@ -23,6 +26,11 @@ class RecaptchaClickTask(TaskPayload, UserAgentPayload): description='Set to true if you want to solve invisible reCAPTCHA.') proxy: Optional[ProxyPayload] = Field(default=None, description='Proxy settings.') + def model_post_init(self, __context: Any) -> None: + warn_deprecated("RecaptchaClickTask is deprecated and will be removed in 6.0: " + "CapMonster Cloud documents no 'RecaptchaClickTask' type. " + "Use ComplexImageRecaptchaTask for reCAPTCHA (click).", stacklevel=4) + def to_request(self) -> dict[str, Any]: base = self.model_dump(exclude_none=True) proxy_dict = base.pop("proxy", {}) diff --git a/src/capmonster_python/tasks/recaptcha_v2_enterprise.py b/src/capmonster_python/tasks/recaptcha_v2_enterprise.py index 48bb22d..58151ae 100644 --- a/src/capmonster_python/tasks/recaptcha_v2_enterprise.py +++ b/src/capmonster_python/tasks/recaptcha_v2_enterprise.py @@ -17,6 +17,7 @@ class RecaptchaV2EnterpriseTask(TaskPayload, UserAgentPayload): apiDomain: An optional domain address from which to load reCAPTCHA Enterprise. This parameter should only be set if explicitly needed. cookies: Optional cookies to be sent with the request. + minScore: Optional minimum acceptable score, from 0.1 to 0.9. proxy: Optional proxy settings for handling the task. """ type: str = Field(default="RecaptchaV2EnterpriseTask", frozen=True) @@ -31,6 +32,7 @@ class RecaptchaV2EnterpriseTask(TaskPayload, UserAgentPayload): apiDomain: Optional[str] = Field(default=None, description='Domain address from which to load reCAPTCHA Enterprise. ' 'Don\'t use a parameter if you don\'t know why it\'s needed.') + minScore: Optional[float] = Field(default=None, description='Minimum score of a captcha.', ge=0.1, le=0.9) cookies: Optional[str] = Field(default=None, description='Cookies to be sent with the request.') nocache: Optional[bool] = Field(default=None, description='Set to true to force fresh token generation (prevents reuse of cached tokens).') diff --git a/src/capmonster_python/tasks/temu.py b/src/capmonster_python/tasks/temu.py index 91f9555..0f7256b 100644 --- a/src/capmonster_python/tasks/temu.py +++ b/src/capmonster_python/tasks/temu.py @@ -3,10 +3,13 @@ from pydantic import Field from .task import TaskPayload, UserAgentPayload +from .._deprecation import warn_deprecated class TemuTask(TaskPayload, UserAgentPayload): """ + Deprecated: will be removed in 6.0. + Represents a Temu task for CAPTCHA challenge handling. Attributes: @@ -21,6 +24,10 @@ class TemuTask(TaskPayload, UserAgentPayload): websiteURL: str = Field(..., description="The full URL of the page where the CAPTCHA is loaded.") cookie: str = Field(..., description="Cookies obtained from the page where the CAPTCHA is loaded.") + def model_post_init(self, __context: Any) -> None: + warn_deprecated("TemuTask is deprecated and will be removed in 6.0: " + "Temu is no longer in the CapMonster Cloud docs.", stacklevel=4) + def to_request(self) -> dict[str, Any]: base = self.model_dump(exclude_none=True, by_alias=True) cookie = base.pop("cookie") diff --git a/src/capmonster_python/tasks/tendi.py b/src/capmonster_python/tasks/tendi.py index c9b2afe..482e2c3 100644 --- a/src/capmonster_python/tasks/tendi.py +++ b/src/capmonster_python/tasks/tendi.py @@ -1,10 +1,22 @@ from typing import Optional, Any -from pydantic import Field +from pydantic import Field, BaseModel from .task import TaskPayload, UserAgentPayload, ProxyPayload +class TenDIMetadata(BaseModel): + """ + Optional metadata for TenDI task. + + Attributes: + captchaUrl: Link to the captcha script, if the site loads it from a custom domain. + aidEncrypted: The single-use encrypted Aid value issued by the site, if it uses one. + """ + captchaUrl: Optional[str] = Field(default=None, description="Link to the captcha script.") + aidEncrypted: Optional[str] = Field(default=None, description="Single-use encrypted Aid value from the site.") + + class TenDITask(TaskPayload, UserAgentPayload): """ Represents a task configuration for solving a captcha using the TenDI service. @@ -13,6 +25,7 @@ class TenDITask(TaskPayload, UserAgentPayload): class_: Represents the class name of the task. Default is "TenDI". websiteURL: Address of the page on which the captcha is solved. websiteKey: A unique identifier (captchaAppId) specific to the site. + metadata: Optional. TenDI-specific metadata (captchaUrl, aidEncrypted). proxy: Optional. Proxy settings for the task, if applicable. """ type: str = Field(default="CustomTask", frozen=True) @@ -20,11 +33,14 @@ class TenDITask(TaskPayload, UserAgentPayload): websiteURL: str = Field(..., description="Address of the page on which the captcha is solved.") websiteKey: str = Field(..., description="captchaAppId. For example websiteKey: 189123456 - is a " "unique parameter for your site.") - proxy: Optional[ProxyPayload] = Field(..., description="Proxy settings.") + metadata: Optional[TenDIMetadata] = Field(default=None, description="TenDI-specific metadata.") + proxy: Optional[ProxyPayload] = Field(default=None, description="Proxy settings.") def to_request(self) -> dict[str, Any]: base = self.model_dump(exclude_none=True, by_alias=True) proxy_dict = base.pop("proxy", {}) if proxy_dict: base.update(proxy_dict) + if base.get("metadata") == {}: + base.pop("metadata") return base diff --git a/src/capmonster_python/tasks/turnstile.py b/src/capmonster_python/tasks/turnstile.py index 18d9654..d974f2e 100644 --- a/src/capmonster_python/tasks/turnstile.py +++ b/src/capmonster_python/tasks/turnstile.py @@ -40,10 +40,11 @@ class TurnstileCloudFlareTask(TurnstileTask): values are "token" or "cf_clearance". userAgent: Browser User-Agent string, must originate from a Windows OS. apiJsUrl: Optional captcha script URL, applicable only for "token" type tasks. + pageData: Optional "chlPageData" value of the challenge, applicable only for "token" type tasks. htmlPageBase64: Base64-encoded HTML page content, required for tasks with "cf_clearance" type. proxy: Optional proxy settings; mandatory for the "cf_clearance" type and - omitted for the "token" type. + optional for the "token" type. Raises: CapmonsterValidationException: When field requirements specific to the `cloudflareTaskType` @@ -54,6 +55,8 @@ class TurnstileCloudFlareTask(TurnstileTask): description="Type of Cloudflare challenge") userAgent: str = Field(..., description="Browser User-Agent string (must be from Windows OS)") apiJsUrl: Optional[str] = Field(default=None, description="Captcha script URL (only for token-based tasks)") + pageData: Optional[str] = Field(default=None, + description="chlPageData value of the challenge (only for token-based tasks)") htmlPageBase64: Optional[str] = Field(default=None, description="Base64-encoded HTML page content, required for cf_clearance type") proxy: Optional[ProxyPayload] = Field( @@ -62,12 +65,7 @@ class TurnstileCloudFlareTask(TurnstileTask): @model_validator(mode="after") def check_fields_match_type(self) -> "TurnstileCloudFlareTask": - if self.cloudflareTaskType == "token": - if not self.apiJsUrl: - raise CapmonsterValidationException("apiJsUrl is required for cloudflareTaskType='token'") - if self.proxy is not None: - raise CapmonsterValidationException("proxy must be omitted for cloudflareTaskType='token'") - elif self.cloudflareTaskType == "cf_clearance": + if self.cloudflareTaskType == "cf_clearance": if not self.htmlPageBase64: raise CapmonsterValidationException("htmlPageBase64 is required for cloudflareTaskType='cf_clearance'") if self.proxy is None: diff --git a/tests/alibaba_test.py b/tests/alibaba_test.py new file mode 100644 index 0000000..e128b80 --- /dev/null +++ b/tests/alibaba_test.py @@ -0,0 +1,33 @@ +import pytest + +from capmonster_python import AlibabaTask, AlibabaMetadata, CapmonsterValidationException + + +def test_to_request(): + task = AlibabaTask( + websiteURL="https://www.example.com", + userAgent="ua", + metadata=AlibabaMetadata(sceneId="1ww7426c", prefix="dlw3kug", region="sgp") + ) + assert task.to_request() == { + "type": "CustomTask", + "class": "alibaba", + "websiteURL": "https://www.example.com", + "userAgent": "ua", + "metadata": {"sceneId": "1ww7426c", "prefix": "dlw3kug", "region": "sgp"} + } + + +def test_punish_url_replaces_scene_id_and_prefix(): + task = AlibabaTask( + websiteURL="https://www.example.com", + metadata=AlibabaMetadata(punishUrl="https://example.com/_____tmd_____/punish?x5secdata=abc", + cookieRequired=True) + ) + assert task.to_request()["metadata"] == {"punishUrl": "https://example.com/_____tmd_____/punish?x5secdata=abc", + "cookieRequired": True} + + +def test_scene_id_and_prefix_required(): + with pytest.raises(CapmonsterValidationException): + AlibabaMetadata(sceneId="only") diff --git a/tests/arcaptcha_test.py b/tests/arcaptcha_test.py new file mode 100644 index 0000000..7325cb2 --- /dev/null +++ b/tests/arcaptcha_test.py @@ -0,0 +1,11 @@ +from capmonster_python import ARCaptchaTask + + +def test_to_request(): + task = ARCaptchaTask(websiteURL="https://example.com", websiteKey="key", isInvisible=True) + assert task.to_request() == {"type": "ArCaptchaTask", "websiteURL": "https://example.com", + "websiteKey": "key", "isInvisible": True} + + +def test_minimal(): + assert "isInvisible" not in ARCaptchaTask(websiteURL="https://example.com", websiteKey="key").to_request() diff --git a/tests/client_mock_test.py b/tests/client_mock_test.py index 2a6017b..72d89e9 100644 --- a/tests/client_mock_test.py +++ b/tests/client_mock_test.py @@ -6,7 +6,7 @@ CapmonsterClient, RecaptchaV2Task, RecaptchaV2EnterpriseTask, RecaptchaV3Task, RecaptchaV3EnterpriseTask, CapmonsterAPIException, CapmonsterException, ProxyPayload, - FunCaptchaTask, RecaptchaClickTask, HuntTask + FunCaptchaTask, RecaptchaClickTask, HuntTask, TaskResult ) BASE_URL = "https://api.capmonster.cloud" @@ -606,3 +606,73 @@ def test_recaptcha_v3_is_enterprise_false(): ) result = task.to_request() assert result["isEnterprise"] is False + + +def test_deprecated_tasks_warn(): + from capmonster_python import TemuTask, CastleTask, CastleMetadata + with pytest.warns(DeprecationWarning, match="ComplexImageRecaptchaTask"): + RecaptchaClickTask(websiteURL="https://example.com", websiteKey="key123") + with pytest.warns(DeprecationWarning, match="TemuTask"): + TemuTask(websiteURL="https://example.com", cookie="c") + with pytest.warns(DeprecationWarning, match="CastleTask"): + CastleTask(websiteURL="https://example.com", websiteKey="pk", + metadata=CastleMetadata(wUrl="https://w", swUrl="https://sw")) + + +READY_WITH_COST = {"errorId": 0, "status": "ready", "cost": 0.0003, "solution": {"text": "answer"}} + + +@respx.mock +def test_get_task_result_detailed_returns_cost(): + respx.post(f"{BASE_URL}/getTaskResult").mock(return_value=Response(200, json=READY_WITH_COST)) + client = CapmonsterClient("test_key") + result = client.get_task_result_detailed(123) + assert result == TaskResult(status="ready", solution={"text": "answer"}, cost=0.0003) + assert client.get_task_result(123) == {"text": "answer"} + + +@respx.mock +def test_get_task_result_detailed_processing(): + respx.post(f"{BASE_URL}/getTaskResult").mock( + return_value=Response(200, json={"errorId": 0, "status": "processing"}) + ) + result = CapmonsterClient("test_key").get_task_result_detailed(123) + assert result.status == "processing" + assert result.solution == {} + assert result.cost is None + + +@respx.mock +def test_solve_detailed_polls_then_returns_cost(): + respx.post(f"{BASE_URL}/createTask").mock(return_value=Response(200, json={"errorId": 0, "taskId": 1})) + respx.post(f"{BASE_URL}/getTaskResult").side_effect = [ + Response(200, json={"errorId": 0, "status": "processing"}), + Response(200, json=READY_WITH_COST), + ] + client = CapmonsterClient("test_key", retry_delay=0) + result = client.solve_detailed(RecaptchaV2Task(websiteURL="https://example.com", websiteKey="key123")) + assert result.cost == 0.0003 + assert result.solution == {"text": "answer"} + + +@respx.mock +def test_solve_keeps_returning_only_the_solution(): + respx.post(f"{BASE_URL}/createTask").mock(return_value=Response(200, json={"errorId": 0, "taskId": 1})) + respx.post(f"{BASE_URL}/getTaskResult").mock(return_value=Response(200, json=READY_WITH_COST)) + client = CapmonsterClient("test_key", retry_delay=0) + assert client.solve(RecaptchaV2Task(websiteURL="https://example.com", websiteKey="key123")) == {"text": "answer"} + + +@respx.mock +@pytest.mark.asyncio +async def test_solve_detailed_async_returns_cost(): + respx.post(f"{BASE_URL}/createTask").mock(return_value=Response(200, json={"errorId": 0, "taskId": 1})) + respx.post(f"{BASE_URL}/getTaskResult").side_effect = [ + Response(200, json={"errorId": 0, "status": "processing"}), + Response(200, json=READY_WITH_COST), + Response(200, json=READY_WITH_COST), + ] + client = CapmonsterClient("test_key", retry_delay=0) + result = await client.solve_detailed_async(RecaptchaV2Task(websiteURL="https://example.com", websiteKey="k")) + assert result.cost == 0.0003 + assert await client.get_task_result_async(1) == {"text": "answer"} diff --git a/tests/complex_image_recognition_test.py b/tests/complex_image_recognition_test.py index 5367b3a..4130575 100644 --- a/tests/complex_image_recognition_test.py +++ b/tests/complex_image_recognition_test.py @@ -10,3 +10,33 @@ def test_to_request(): assert result["type"] == "ComplexImageTask" assert result["class"] == "recognition" assert result["metadata"]["Task"] == "oocl_rotate_double_new" + + +def test_task_argument_is_sent(): + task = ComplexImageRecognitionTask(imagesBase64=["img"], task="bls_3x3", taskArgument="123") + assert task.to_request()["metadata"] == {"Task": "bls_3x3", "TaskArgument": "123"} + + +def test_task_argument_required(): + import pytest + from capmonster_python import CapmonsterValidationException + with pytest.raises(CapmonsterValidationException): + ComplexImageRecognitionTask(imagesBase64=["img"], task="portugal_text_find_icon") + + +def test_bills_audio_sets_payload_type(): + task = ComplexImageRecognitionTask(imagesBase64=["audio"], task="bills_audio") + assert task.to_request()["metadata"] == {"Task": "bills_audio", "PayloadType": "Audio"} + + +def test_new_task_names(): + for name in ("baidu", "dli", "MathSum"): + task = ComplexImageRecognitionTask(imagesBase64=["img"], task=name) + assert task.to_request()["metadata"]["Task"] == name + + +def test_legacy_bls_warns_and_keeps_request(): + import pytest + with pytest.warns(DeprecationWarning, match="bls_3x3"): + task = ComplexImageRecognitionTask(imagesBase64=["img"], task="bls") + assert task.to_request()["metadata"] == {"Task": "bls"} diff --git a/tests/datadome_test.py b/tests/datadome_test.py index 260cbc7..5d26ff5 100644 --- a/tests/datadome_test.py +++ b/tests/datadome_test.py @@ -41,3 +41,18 @@ async def test_create_task_async(): client = CapmonsterClient(API_KEY, timeout=30.0) task_id = await client.create_task_async(task=DataDomeTask(websiteURL=WEBSITE_URL, metadata=METADATA)) assert task_id != 0 + + +def test_datadome_version(): + task = DataDomeTask( + websiteURL="https://example.com", + metadata=DataDomeMetadata(captchaUrl="https://geo.captcha-delivery.com/captcha/?x=1", + datadomeCookie="datadome=abc", datadomeVersion="5.1.2") + ) + assert task.to_request()["metadata"]["datadomeVersion"] == "5.1.2" + + +def test_missing_proxy_warns(): + with pytest.warns(UserWarning, match="proxy"): + DataDomeTask(websiteURL="https://example.com", + metadata=DataDomeMetadata(captchaUrl="https://c", datadomeCookie="d")) diff --git a/tests/fengkongcloud_test.py b/tests/fengkongcloud_test.py new file mode 100644 index 0000000..033fd04 --- /dev/null +++ b/tests/fengkongcloud_test.py @@ -0,0 +1,21 @@ +from capmonster_python import FengkongCloudTask, FengkongCloudMetadata + + +def test_to_request(): + task = FengkongCloudTask( + websiteURL="https://example.com", + websiteKey="site_key", + metadata=FengkongCloudMetadata(apiJsUrl="https://castatic.fengkongcloud.com/pr/v1.0.4/smcp.min.js") + ) + assert task.to_request() == { + "type": "CustomTask", + "class": "fengkongcloud", + "websiteURL": "https://example.com", + "websiteKey": "site_key", + "metadata": {"apiJsUrl": "https://castatic.fengkongcloud.com/pr/v1.0.4/smcp.min.js"} + } + + +def test_metadata_optional(): + task = FengkongCloudTask(websiteURL="https://example.com", websiteKey="k", metadata=FengkongCloudMetadata()) + assert "metadata" not in task.to_request() diff --git a/tests/friendly_test.py b/tests/friendly_test.py new file mode 100644 index 0000000..bf1af5b --- /dev/null +++ b/tests/friendly_test.py @@ -0,0 +1,17 @@ +from capmonster_python import FriendlyTask, FriendlyMetadata, ProxyPayload + + +def test_to_request(): + task = FriendlyTask( + websiteURL="https://example.com", + websiteKey="FCMST5VUMCBOCGQ9", + metadata=FriendlyMetadata(apiGetLib="https://cdn.jsdelivr.net/npm/@friendlycaptcha/sdk@0.1.8/site.min.js"), + proxy=ProxyPayload(proxyType="http", proxyAddress="1.2.3.4", proxyPort=8080) + ) + result = task.to_request() + assert result["type"] == "CustomTask" + assert result["class"] == "friendly" + assert result["websiteKey"] == "FCMST5VUMCBOCGQ9" + assert result["metadata"] == {"apiGetLib": "https://cdn.jsdelivr.net/npm/@friendlycaptcha/sdk@0.1.8/site.min.js"} + assert result["proxyPort"] == 8080 + assert "proxy" not in result diff --git a/tests/funcaptcha_test.py b/tests/funcaptcha_test.py index 92a40e7..7a5b382 100644 --- a/tests/funcaptcha_test.py +++ b/tests/funcaptcha_test.py @@ -40,3 +40,9 @@ def test_to_request_minimal(): assert "funcaptchaApiJSSubdomain" not in result assert "data" not in result assert "cookies" not in result + + +def test_missing_proxy_warns(): + import pytest + with pytest.warns(UserWarning, match="proxy"): + FunCaptchaTask(websiteURL="https://example.com", websitePublicKey="key") diff --git a/tests/heytap_test.py b/tests/heytap_test.py new file mode 100644 index 0000000..b3afa8e --- /dev/null +++ b/tests/heytap_test.py @@ -0,0 +1,22 @@ +from capmonster_python import HeyTapTask, HeyTapMetadata + + +def test_to_request(): + task = HeyTapTask( + websiteURL="https://example.com", + websiteKey="key", + userAgent="ua", + metadata=HeyTapMetadata(apiServer="captcha-sec.heytapmobi.com") + ) + assert task.to_request() == { + "type": "CustomTask", + "class": "heytap", + "websiteURL": "https://example.com", + "websiteKey": "key", + "userAgent": "ua", + "metadata": {"apiServer": "captcha-sec.heytapmobi.com"} + } + + +def test_metadata_optional(): + assert "metadata" not in HeyTapTask(websiteURL="https://example.com", websiteKey="key").to_request() diff --git a/tests/hunt_test.py b/tests/hunt_test.py new file mode 100644 index 0000000..b81d3a0 --- /dev/null +++ b/tests/hunt_test.py @@ -0,0 +1,58 @@ +import pytest + +from capmonster_python import HuntTask, HuntMetadata, ProxyPayload, CapmonsterValidationException + +PROXY = ProxyPayload(proxyType="http", proxyAddress="1.2.3.4", proxyPort=8080) + + +def test_to_request_with_data(): + task = HuntTask( + websiteURL="https://example.com", + metadata=HuntMetadata(apiGetLib="https://example.com/hd-api/api.js", data="meta_token"), + proxy=PROXY + ) + result = task.to_request() + assert task.type == "CustomTask" + assert result["type"] == "CustomTask" + assert result["class"] == "HUNT" + assert result["websiteURL"] == "https://example.com" + assert result["metadata"] == {"apiGetLib": "https://example.com/hd-api/api.js", "data": "meta_token"} + assert result["proxyType"] == "http" + assert "proxy" not in result + assert "websiteKey" not in result + + +def test_to_request_with_widget_url(): + task = HuntTask( + websiteURL="https://example.com", + metadata=HuntMetadata(apiGetLib="https://example.com/api.js", widgetUrl="https://captcha.example.com/w?h=1"), + proxy=PROXY + ) + assert task.to_request()["metadata"]["widgetUrl"] == "https://captcha.example.com/w?h=1" + + +def test_x_hd_generation_only_api_get_lib(): + task = HuntTask(websiteURL="https://example.com", metadata=HuntMetadata(apiGetLib="a"), proxy=PROXY) + assert task.to_request()["metadata"] == {"apiGetLib": "a"} + + +def test_data_and_widget_url_together(): + with pytest.raises(CapmonsterValidationException): + HuntMetadata(apiGetLib="a", data="d", widgetUrl="w") + + +def test_proxy_required(): + with pytest.raises(CapmonsterValidationException): + HuntTask(websiteURL="https://example.com", metadata=HuntMetadata(apiGetLib="a")) + + +def test_metadata_or_website_key_required(): + with pytest.raises(CapmonsterValidationException): + HuntTask(websiteURL="https://example.com", proxy=PROXY) + + +def test_legacy_website_key_warns_and_keeps_request(): + with pytest.warns(DeprecationWarning, match="HuntTask"): + task = HuntTask(websiteURL="https://example.com", websiteKey="key123") + assert task.type == "HuntTask" + assert task.to_request() == {"type": "HuntTask", "websiteURL": "https://example.com", "websiteKey": "key123"} diff --git a/tests/imperva_test.py b/tests/imperva_test.py new file mode 100644 index 0000000..16bdf46 --- /dev/null +++ b/tests/imperva_test.py @@ -0,0 +1,48 @@ +import warnings + +import pytest + +from capmonster_python import ImpervaTask, ImpervaTaskMetadata, ProxyPayload + +PROXY = ProxyPayload(proxyType="http", proxyAddress="1.2.3.4", proxyPort=8080) + + +def test_to_request(): + task = ImpervaTask( + websiteURL="https://example.com", + metadata=ImpervaTaskMetadata( + incapsulaScriptUrl="_Incapsula_Resource?SWJIYLWA=abc", + incapsulaCookies="visid_incap_1=x; incap_ses_1=y", + reese84UrlEndpoint="Built-with-the-For-hopence-Hurleysurfecting-the-" + ), + proxy=PROXY + ) + result = task.to_request() + assert result["type"] == "CustomTask" + assert result["class"] == "Imperva" + assert result["metadata"]["incapsulaCookies"] == "visid_incap_1=x; incap_ses_1=y" + assert "incapsulaCookie" not in result["metadata"] + assert result["proxyAddress"] == "1.2.3.4" + assert "proxy" not in result + + +def test_legacy_cookie_name_warns_and_is_renamed(): + with pytest.warns(DeprecationWarning, match="incapsulaCookies"): + metadata = ImpervaTaskMetadata(incapsulaScriptUrl="s", incapsulaCookie="c") + assert metadata.incapsulaCookies == "c" + with pytest.warns(DeprecationWarning): + assert metadata.incapsulaCookie == "c" + task = ImpervaTask(websiteURL="https://example.com", metadata=metadata, proxy=PROXY) + assert task.to_request()["metadata"] == {"incapsulaScriptUrl": "s", "incapsulaCookies": "c"} + + +def test_missing_proxy_warns(): + with pytest.warns(UserWarning, match="proxy"): + ImpervaTask(websiteURL="https://example.com", + metadata=ImpervaTaskMetadata(incapsulaScriptUrl="s", incapsulaCookies="c")) + + +def test_new_cookie_name_does_not_warn(): + with warnings.catch_warnings(): + warnings.simplefilter("error") + ImpervaTaskMetadata(incapsulaScriptUrl="s", incapsulaCookies="c") diff --git a/tests/proton_test.py b/tests/proton_test.py new file mode 100644 index 0000000..92b238e --- /dev/null +++ b/tests/proton_test.py @@ -0,0 +1,35 @@ +import pytest +from pydantic import ValidationError + +from capmonster_python import ProtonTask, ProtonMetadata, ProxyPayload + +PROXY = ProxyPayload(proxyType="http", proxyAddress="8.8.8.8", proxyPort=8080, proxyLogin="l", proxyPassword="p") + + +def test_to_request(): + task = ProtonTask( + websiteURL="https://yourwebsite.com/", + metadata=ProtonMetadata(HumanVerificationToken="token", pageAction="login"), + proxy=PROXY + ) + assert task.to_request() == { + "type": "CustomTask", + "class": "proton", + "websiteURL": "https://yourwebsite.com/", + "metadata": {"HumanVerificationToken": "token", "pageAction": "login"}, + "proxyType": "http", + "proxyAddress": "8.8.8.8", + "proxyPort": 8080, + "proxyLogin": "l", + "proxyPassword": "p" + } + + +def test_proxy_required(): + with pytest.raises(ValidationError): + ProtonTask(websiteURL="https://x", metadata=ProtonMetadata(HumanVerificationToken="t", pageAction="signup")) + + +def test_page_action_values(): + with pytest.raises(ValidationError): + ProtonMetadata(HumanVerificationToken="t", pageAction="register") diff --git a/tests/recaptcha_v2_enterprise_test.py b/tests/recaptcha_v2_enterprise_test.py new file mode 100644 index 0000000..d3a23ea --- /dev/null +++ b/tests/recaptcha_v2_enterprise_test.py @@ -0,0 +1,19 @@ +import pytest +from pydantic import ValidationError + +from capmonster_python import RecaptchaV2EnterpriseTask + + +def test_min_score(): + task = RecaptchaV2EnterpriseTask(websiteURL="https://example.com", websiteKey="key", minScore=0.7) + assert task.to_request()["minScore"] == 0.7 + + +def test_min_score_omitted_by_default(): + task = RecaptchaV2EnterpriseTask(websiteURL="https://example.com", websiteKey="key") + assert "minScore" not in task.to_request() + + +def test_min_score_range(): + with pytest.raises(ValidationError): + RecaptchaV2EnterpriseTask(websiteURL="https://example.com", websiteKey="key", minScore=1.5) diff --git a/tests/tendi_test.py b/tests/tendi_test.py new file mode 100644 index 0000000..84c85f9 --- /dev/null +++ b/tests/tendi_test.py @@ -0,0 +1,28 @@ +from capmonster_python import TenDITask, TenDIMetadata + + +def test_to_request_minimal(): + task = TenDITask(websiteURL="https://example.com", websiteKey="189123456") + result = task.to_request() + assert result == {"type": "CustomTask", "class": "TenDI", "websiteURL": "https://example.com", + "websiteKey": "189123456"} + + +def test_to_request_with_metadata(): + task = TenDITask( + websiteURL="https://example.com", + websiteKey="189123456", + metadata=TenDIMetadata(captchaUrl="https://global.captcha.example.com/TCaptcha.js", aidEncrypted="enc") + ) + assert task.to_request()["metadata"] == {"captchaUrl": "https://global.captcha.example.com/TCaptcha.js", + "aidEncrypted": "enc"} + + +def test_empty_metadata_is_omitted(): + task = TenDITask(websiteURL="https://example.com", websiteKey="1", metadata=TenDIMetadata()) + assert "metadata" not in task.to_request() + + +def test_explicit_none_proxy_still_works(): + task = TenDITask(websiteURL="https://example.com", websiteKey="1", proxy=None) + assert "proxyType" not in task.to_request() diff --git a/tests/turnstile_cloudflare_test.py b/tests/turnstile_cloudflare_test.py new file mode 100644 index 0000000..d930475 --- /dev/null +++ b/tests/turnstile_cloudflare_test.py @@ -0,0 +1,31 @@ +from capmonster_python import TurnstileCloudFlareTask, ProxyPayload + +UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36" + + +def test_token_with_page_data(): + task = TurnstileCloudFlareTask( + websiteURL="https://example.com", + websiteKey="0x4AAAAAAA", + userAgent=UA, + pageAction="managed", + data="cdata", + pageData="chl_page_data", + apiJsUrl="https://challenges.cloudflare.com/turnstile/v0/g/api.js" + ) + result = task.to_request() + assert result["type"] == "TurnstileTask" + assert result["cloudflareTaskType"] == "token" + assert result["pageData"] == "chl_page_data" + + +def test_token_without_api_js_url_and_with_proxy(): + task = TurnstileCloudFlareTask( + websiteURL="https://example.com", + websiteKey="0x4AAAAAAA", + userAgent=UA, + proxy=ProxyPayload(proxyType="http", proxyAddress="1.2.3.4", proxyPort=8080) + ) + result = task.to_request() + assert "apiJsUrl" not in result + assert result["proxyAddress"] == "1.2.3.4"