Skip to main content

anticaptcha/
blocking.rs

1//! Synchronous mirror of the async API, behind the `blocking` feature.
2//!
3//! Every method has the same name and takes the same arguments as its
4//! [`crate::Client`] counterpart, it just blocks instead of returning a future.
5//!
6//! ```no_run
7//! use anticaptcha::blocking::Client;
8//! use anticaptcha::RecaptchaV2;
9//!
10//! # fn run() -> anticaptcha::Result<()> {
11//! let ac = Client::new("API_KEY_HERE")?;
12//!
13//! let solution = ac.solve_recaptcha_v2(&RecaptchaV2 {
14//!     website_url: "https://www.website.com/".into(),
15//!     website_key: "SITE_KEY".into(),
16//!     ..Default::default()
17//! })?;
18//!
19//! println!("{}", solution.g_recaptcha_response());
20//! # Ok(())
21//! # }
22//! ```
23//!
24//! # Do not call this from inside an async runtime
25//!
26//! The blocking client drives its own Tokio runtime, and nesting runtimes
27//! panics. If your program is already async, use [`crate::Client`] directly.
28
29use std::path::Path;
30use std::time::Duration;
31
32use serde_json::Value;
33
34use crate::error::{Error, Result};
35use crate::solution::Solution;
36use crate::tasks;
37
38/// Forwards a set of async methods to their blocking counterparts.
39macro_rules! forward {
40    ($( $(#[$meta:meta])* $name:ident ( $($arg:ident : $ty:ty),* ) -> $ret:ty; )*) => {
41        $(
42            $(#[$meta])*
43            pub fn $name(&self, $($arg: $ty),*) -> Result<$ret> {
44                self.runtime.block_on(self.inner.$name($($arg),*))
45            }
46        )*
47    };
48}
49
50/// Synchronous Anti-Captcha client.
51#[derive(Debug)]
52pub struct Client {
53    inner: crate::Client,
54    runtime: tokio::runtime::Runtime,
55}
56
57impl Client {
58    /// Creates a client and the runtime that drives it.
59    ///
60    /// Fails only when the Tokio runtime cannot be started.
61    pub fn new(api_key: impl Into<String>) -> Result<Self> {
62        Self::from_async(crate::Client::new(api_key))
63    }
64
65    /// Wraps an already configured async client.
66    pub fn from_async(inner: crate::Client) -> Result<Self> {
67        let runtime = tokio::runtime::Builder::new_current_thread()
68            .enable_all()
69            .build()
70            .map_err(|source| Error::Io {
71                path: "tokio runtime".into(),
72                source,
73            })?;
74
75        Ok(Self { inner, runtime })
76    }
77
78    /// The async client underneath, for the settings builders.
79    pub fn inner(&self) -> &crate::Client {
80        &self.inner
81    }
82
83    pub fn set_api_key(&mut self, api_key: impl Into<String>) {
84        self.inner.set_api_key(api_key);
85    }
86
87    /// Applies a builder method of the async client, e.g.
88    /// `client.configure(|c| c.with_soft_id(1187).quiet())`.
89    pub fn configure(&mut self, change: impl FnOnce(crate::Client) -> crate::Client) {
90        let current = self.inner.clone();
91        self.inner = change(current);
92    }
93
94    /// Reads a file and encodes it in base64.
95    pub fn file_to_base64(path: impl AsRef<Path>) -> Result<String> {
96        crate::Client::file_to_base64(path)
97    }
98
99    /// Encodes bytes in base64.
100    pub fn to_base64(bytes: impl AsRef<[u8]>) -> String {
101        crate::Client::to_base64(bytes)
102    }
103
104    forward! {
105        /// Account balance in US dollars.
106        get_balance() -> f64;
107        /// Number of prepaid captcha credits on the account.
108        get_credits_balance() -> f64;
109
110        /// Calls any API method with your own payload.
111        json_request(method: &str, payload: Value) -> Value;
112        /// Submits a task and returns its id.
113        create_task(task: Value) -> i64;
114        /// Polls until the task is solved or the waiting limit runs out.
115        wait_for_result(task_id: i64) -> Solution;
116        /// Sends a task type this library does not wrap yet.
117        solve_task(task: Value) -> Solution;
118
119        solve_image(base64_body: &str, settings: &tasks::ImageSettings) -> Solution;
120        solve_image_to_coordinates(base64_body: &str, settings: &tasks::ImageToCoordinates) -> Solution;
121        solve_recaptcha_v2(settings: &tasks::RecaptchaV2) -> Solution;
122        solve_recaptcha_v2_proxy_on(settings: &tasks::RecaptchaV2) -> Solution;
123        solve_recaptcha_v3(settings: &tasks::RecaptchaV3) -> Solution;
124        solve_hcaptcha(settings: &tasks::HCaptcha) -> Solution;
125        solve_hcaptcha_proxy_on(settings: &tasks::HCaptcha) -> Solution;
126        solve_funcaptcha(settings: &tasks::FunCaptcha) -> Solution;
127        solve_funcaptcha_proxy_on(settings: &tasks::FunCaptcha) -> Solution;
128        solve_geetest(settings: &tasks::GeeTest) -> Solution;
129        solve_geetest_proxy_on(settings: &tasks::GeeTest) -> Solution;
130        solve_turnstile(settings: &tasks::Turnstile) -> Solution;
131        solve_turnstile_proxy_on(settings: &tasks::Turnstile) -> Solution;
132        solve_prosopo(settings: &tasks::Prosopo) -> Solution;
133        solve_prosopo_proxy_on(settings: &tasks::Prosopo) -> Solution;
134        solve_friendly_captcha(settings: &tasks::FriendlyCaptcha) -> Solution;
135        solve_friendly_captcha_proxy_on(settings: &tasks::FriendlyCaptcha) -> Solution;
136        solve_altcha(settings: &tasks::Altcha) -> Solution;
137        solve_altcha_proxy_on(settings: &tasks::Altcha) -> Solution;
138        solve_amazon(settings: &tasks::Amazon) -> Solution;
139        solve_amazon_proxy_on(settings: &tasks::Amazon) -> Solution;
140        solve_antigate(settings: &tasks::AntiGate) -> Solution;
141        solve_antibot_cookie(settings: &tasks::AntiBotCookie) -> Solution;
142
143        report_incorrect_image_captcha(task_id: i64) -> ();
144        report_incorrect_recaptcha(task_id: i64) -> ();
145        report_correct_recaptcha(task_id: i64) -> ();
146        report_incorrect_hcaptcha(task_id: i64) -> ();
147    }
148
149    /// Solves an image captcha read from a file.
150    pub fn solve_image_file(
151        &self,
152        path: impl AsRef<Path>,
153        settings: &tasks::ImageSettings,
154    ) -> Result<Solution> {
155        self.runtime
156            .block_on(self.inner.solve_image_file(path, settings))
157    }
158
159    /// Solves an image-to-coordinates captcha read from a file.
160    pub fn solve_image_to_coordinates_file(
161        &self,
162        path: impl AsRef<Path>,
163        settings: &tasks::ImageToCoordinates,
164    ) -> Result<Solution> {
165        self.runtime
166            .block_on(self.inner.solve_image_to_coordinates_file(path, settings))
167    }
168
169    /// How long to keep polling before giving up. Default 300 seconds.
170    pub fn set_max_waiting_time(&mut self, timeout: Duration) {
171        self.configure(|client| client.with_max_waiting_time(timeout));
172    }
173}
174
175#[cfg(test)]
176mod tests {
177    use super::*;
178
179    #[test]
180    fn empty_api_key_is_refused() {
181        let client = Client::from_async(crate::Client::new("").quiet()).unwrap();
182        let error = client.get_balance().unwrap_err();
183
184        assert!(matches!(error, Error::InvalidTask(_)));
185    }
186
187    #[test]
188    fn configure_replaces_the_inner_client() {
189        let mut client = Client::from_async(crate::Client::new("").quiet()).unwrap();
190        client.set_max_waiting_time(Duration::from_secs(42));
191        client.configure(|inner| inner.with_soft_id(1187));
192        client.set_api_key("KEY");
193
194        // The settings are private, so just check the client is still usable and
195        // still validates before touching the network.
196        let error = client.solve_altcha(&crate::Altcha::default()).unwrap_err();
197
198        assert!(matches!(error, Error::InvalidTask(_)));
199    }
200}