Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,14 @@ All notable changes to this crate are documented here. The format follows
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/), versions follow [SemVer](https://semver.org/)
(while the major version is 0, a breaking change bumps the **minor** number).

## [0.3.0]

### Added
- `SolvedTask` (`solution` and optional `cost` in USD from `getTaskResult`).

### Changed
- `TaskStatus::Ready` now carries a `SolvedTask`, and `solve_captcha` returns `SolvedTask` instead of the bare solution `Value`.

## [0.2.0]

### Added
Expand Down
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "capmonstercloud-client"
version = "0.2.0"
version = "0.3.0"
edition = "2021"
rust-version = "1.88"
description = "Async Rust client for the CapMonster Cloud captcha-solving API"
Expand Down
22 changes: 12 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -106,9 +106,11 @@ async fn main() -> capmonstercloud_client::Result<()> {
"6Lcg7CMUAAAAANphynKgn9YAgA4tQ2KI_iqRyTwd",
);

// Send task and receive token (the `solution` object as serde_json::Value)
let solution = client.solve_captcha(&request).await?;
println!("reCAPTCHA Token: {}", solution["gRecaptchaResponse"]);
// Send task and receive token (`solved.solution` is the solution object as serde_json::Value)
let solved = client.solve_captcha(&request).await?;
println!("reCAPTCHA Token: {}", solved.solution["gRecaptchaResponse"]);
// Solution cost in USD (None if the API did not return it)
println!("Cost: {:?}", solved.cost);
Ok(())
}
```
Expand All @@ -130,9 +132,9 @@ async fn main() -> capmonstercloud_client::Result<()> {
TurnstileStandard::new().with_proxy(proxy),
);

let solution = client.solve_captcha(&request).await?;
// inject solution["token"] into the cf-turnstile-response field of your browser session and submit
println!("Turnstile token: {}", solution["token"]);
let solved = client.solve_captcha(&request).await?;
// inject solved.solution["token"] into the cf-turnstile-response field of your browser session and submit
println!("Turnstile token: {}", solved.solution["token"]);
Ok(())
}
```
Expand All @@ -146,7 +148,7 @@ println!("balance: {}", client.get_balance().await?);
let task_id = client.create_task(&request).await?;
match client.get_task_result(task_id).await? {
TaskStatus::Processing => println!("not ready yet"),
TaskStatus::Ready(solution) => println!("{solution}"),
TaskStatus::Ready(solved) => println!("{} (cost: {:?})", solved.solution, solved.cost),
}
```

Expand Down Expand Up @@ -178,8 +180,8 @@ async fn main() -> capmonstercloud_client::Result<()> {
"YOUR_SITE_KEY",
);

let solution = client.solve_captcha(&request).await?;
let token = solution["gRecaptchaResponse"].as_str().unwrap_or_default();
let solved = client.solve_captcha(&request).await?;
let token = solved.solution["gRecaptchaResponse"].as_str().unwrap_or_default();
println!("{token}");
Ok(())
}
Expand Down Expand Up @@ -279,7 +281,7 @@ Add `capmonstercloud-client` to `Cargo.toml`, create a `CapMonsterClient` with y
Yes. This repository is the official Rust client library for the CapMonster Cloud captcha solving service.

**How do I bypass reCAPTCHA v2 in Rust?**
Create a client, build a `RecaptchaV2Request` with the page URL and sitekey, call `client.solve_captcha(&request).await?` and read `solution["gRecaptchaResponse"]`. See the [reCAPTCHA v2 documentation](https://docs.capmonster.cloud/docs/captchas/no-captcha-task/?utm_source=github&utm_medium=referral&utm_campaign=rust_repo_readme).
Create a client, build a `RecaptchaV2Request` with the page URL and sitekey, call `client.solve_captcha(&request).await?` and read `solved.solution["gRecaptchaResponse"]`. See the [reCAPTCHA v2 documentation](https://docs.capmonster.cloud/docs/captchas/no-captcha-task/?utm_source=github&utm_medium=referral&utm_campaign=rust_repo_readme).

**How do I bypass Cloudflare Turnstile in Rust?**
Use `TurnstileRequest` with `TurnstileStandard` (optionally with a proxy), as in example 2 above. According to the [Turnstile documentation](https://docs.capmonster.cloud/docs/captchas/turnstile-task/?utm_source=github&utm_medium=referral&utm_campaign=rust_repo_readme), all Turnstile subtypes are supported automatically: manual, non-interactive and invisible.
Expand Down
2 changes: 1 addition & 1 deletion examples/image_to_text.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,6 @@ async fn main() -> capmonstercloud_client::Result<()> {
println!("balance: {}", client.get_balance().await?);

let request = ImageToTextRequest::new(image).with_module_name(TextModule::Universal);
println!("{}", client.solve_captcha(&request).await?);
println!("{}", client.solve_captcha(&request).await?.solution);
Ok(())
}
5 changes: 3 additions & 2 deletions examples/recaptcha_v2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ async fn main() -> capmonstercloud_client::Result<()> {
"https://lessons.zennolab.com/captchas/recaptcha/v2_simple.php?level=high",
"6Lcg7CMUAAAAANphynKgn9YAgA4tQ2KI_iqRyTwd",
);
let solution = client.solve_captcha(&request).await?;
println!("{solution}");
let solved = client.solve_captcha(&request).await?;
println!("{}", solved.solution);
println!("cost: {:?}", solved.cost);
Ok(())
}
28 changes: 21 additions & 7 deletions src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ struct ApiResponse {
status: Option<String>,
solution: Option<Value>,
balance: Option<f64>,
cost: Option<f64>,
}

impl ApiResponse {
Expand All @@ -105,12 +106,21 @@ impl ApiResponse {
}
}

/// A solved task: the `solution` object and the solving cost.
#[derive(Debug, Clone, PartialEq)]
pub struct SolvedTask {
/// The solution object; its shape depends on the captcha type.
pub solution: Value,
/// Solution cost in US dollars (`cost` of `getTaskResult`); `None` if the API did not return it.
pub cost: Option<f64>,
}

/// State of a task returned by [`CapMonsterClient::get_task_result`].
#[derive(Debug, Clone, PartialEq)]
pub enum TaskStatus {
Processing,
/// The solution object; its shape depends on the captcha type.
Ready(Value),
/// The solution and its cost.
Ready(SolvedTask),
}

/// Asynchronous CapMonster Cloud client. Cheap to clone (the HTTP pool is shared).
Expand Down Expand Up @@ -203,15 +213,19 @@ impl CapMonsterClient {
});
}
match resp.status.as_deref() {
Some("ready") => Ok(TaskStatus::Ready(resp.solution.unwrap_or(Value::Null))),
Some("ready") => Ok(TaskStatus::Ready(SolvedTask {
solution: resp.solution.unwrap_or(Value::Null),
cost: resp.cost,
})),
_ => Ok(TaskStatus::Processing),
}
}

/// Creates a task, polls until it is solved and returns the `solution` object.
/// Creates a task, polls until it is solved and returns the `solution` object
/// together with the cost.
///
/// Returns `Error::Timeout` if the captcha type's maximum waiting time is exceeded.
pub async fn solve_captcha<R: CaptchaRequest>(&self, request: &R) -> Result<Value> {
pub async fn solve_captcha<R: CaptchaRequest>(&self, request: &R) -> Result<SolvedTask> {
let timeouts = self
.options
.timeouts_override
Expand All @@ -225,8 +239,8 @@ impl CapMonsterClient {
.unwrap_or_else(|| now + Duration::from_secs(365 * 24 * 3600));
sleep(timeouts.first_request_delay).await;
while Instant::now() < deadline {
if let TaskStatus::Ready(solution) = self.get_task_result(task_id).await? {
return Ok(solution);
if let TaskStatus::Ready(solved) = self.get_task_result(task_id).await? {
return Ok(solved);
}
sleep(timeouts.requests_interval).await;
}
Expand Down
6 changes: 3 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@
//! "https://lessons.zennolab.com/captchas/recaptcha/v2_simple.php?level=high",
//! "6Lcg7CMUAAAAANphynKgn9YAgA4tQ2KI_iqRyTwd",
//! );
//! let solution = client.solve_captcha(&request).await?;
//! println!("{}", solution["gRecaptchaResponse"]);
//! let solved = client.solve_captcha(&request).await?;
//! println!("{}", solved.solution["gRecaptchaResponse"]);
//! # Ok(()) }
//! ```

Expand All @@ -22,7 +22,7 @@ pub mod requests;
mod timeouts;

pub use client::{
CapMonsterClient, ClientOptions, TaskStatus, DEFAULT_SERVICE_URL, DEFAULT_SOFT_ID,
CapMonsterClient, ClientOptions, SolvedTask, TaskStatus, DEFAULT_SERVICE_URL, DEFAULT_SOFT_ID,
};
pub use error::{Error, Result};
pub use proxy::{ClientProxy, ProxyInfo, ProxyType};
Expand Down
75 changes: 72 additions & 3 deletions tests/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ use std::time::Duration;

use capmonstercloud_client::requests::RecaptchaV2Request;
use capmonstercloud_client::{
CapMonsterClient, ClientOptions, ClientProxy, Error, GetResultTimeouts, ProxyType, TaskStatus,
CapMonsterClient, ClientOptions, ClientProxy, Error, GetResultTimeouts, ProxyType, SolvedTask,
TaskStatus,
};
use serde_json::json;
use wiremock::matchers::{body_partial_json, header_exists, method, path};
Expand Down Expand Up @@ -61,11 +62,12 @@ async fn solve_captcha_creates_task_and_polls_until_ready() {
.mount(&server)
.await;

let solution = fast_client(&server)
let solved = fast_client(&server)
.solve_captcha(&request())
.await
.unwrap();
assert_eq!(solution["gRecaptchaResponse"], "TOKEN");
assert_eq!(solved.solution["gRecaptchaResponse"], "TOKEN");
assert_eq!(solved.cost, None);
}

#[tokio::test]
Expand Down Expand Up @@ -166,6 +168,73 @@ async fn get_balance_returns_number() {
assert_eq!(fast_client(&server).get_balance().await.unwrap(), 12.5);
}

#[tokio::test]
async fn get_task_result_ready_returns_cost() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/getTaskResult"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"errorId": 0, "status": "ready", "cost": 0.0003,
"solution": {"gRecaptchaResponse": "TOKEN"}
})))
.mount(&server)
.await;

let status = fast_client(&server).get_task_result(7).await.unwrap();
assert_eq!(
status,
TaskStatus::Ready(SolvedTask {
solution: json!({"gRecaptchaResponse": "TOKEN"}),
cost: Some(0.0003),
})
);
}

#[tokio::test]
async fn get_task_result_ready_without_cost_has_none() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/getTaskResult"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"errorId": 0, "status": "ready", "solution": {"text": "abc"}
})))
.mount(&server)
.await;

let status = fast_client(&server).get_task_result(7).await.unwrap();
assert_eq!(
status,
TaskStatus::Ready(SolvedTask {
solution: json!({"text": "abc"}),
cost: None,
})
);
}

#[tokio::test]
async fn solve_captcha_returns_cost() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/createTask"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"errorId": 0, "taskId": 5})))
.mount(&server)
.await;
Mock::given(method("POST"))
.and(path("/getTaskResult"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"errorId": 0, "status": "ready", "cost": 0.0003,
"solution": {"gRecaptchaResponse": "TOKEN"}
})))
.mount(&server)
.await;

let solved = fast_client(&server)
.solve_captcha(&request())
.await
.unwrap();
assert_eq!(solved.cost, Some(0.0003));
}

#[tokio::test]
async fn invalid_request_fails_before_any_http_call() {
// No mock mounted: any HTTP call would return 404 and be reported as Error::Status.
Expand Down
Loading