Skip to main content

anticaptcha/
client.rs

1//! The async API client.
2
3use std::time::{Duration, Instant};
4
5use base64::engine::general_purpose::STANDARD as BASE64;
6use base64::Engine as _;
7use serde_json::{json, Value};
8
9use crate::error::{Error, Result};
10use crate::solution::Solution;
11use crate::tasks;
12
13const API_HOST: &str = "https://api.anti-captcha.com/";
14
15/// Talks to the Anti-Captcha API.
16///
17/// The client holds no per-task state, so one instance can solve any number of
18/// captchas concurrently. Cloning is cheap: the underlying connection pool is
19/// shared.
20#[derive(Debug, Clone)]
21pub struct Client {
22    http: reqwest::Client,
23    api_key: String,
24    soft_id: i64,
25    verbose: bool,
26    connection_timeout: Duration,
27    first_attempt_waiting_interval: Duration,
28    normal_waiting_interval: Duration,
29    max_waiting_time: Duration,
30}
31
32impl Client {
33    /// Creates a client for the given key from
34    /// <https://anti-captcha.com/clients/settings/apisetup>.
35    pub fn new(api_key: impl Into<String>) -> Self {
36        Self {
37            http: reqwest::Client::new(),
38            api_key: api_key.into(),
39            soft_id: 0,
40            verbose: true,
41            connection_timeout: Duration::from_secs(30),
42            first_attempt_waiting_interval: Duration::from_secs(5),
43            normal_waiting_interval: Duration::from_secs(5),
44            max_waiting_time: Duration::from_secs(300),
45        }
46    }
47
48    /// Reuses an existing `reqwest` client, so the connection pool, proxy and
49    /// TLS settings are shared with the rest of your program.
50    pub fn with_http_client(mut self, http: reqwest::Client) -> Self {
51        self.http = http;
52        self
53    }
54
55    pub fn set_api_key(&mut self, api_key: impl Into<String>) {
56        self.api_key = api_key.into();
57    }
58
59    /// Specify a soft id to earn 10% commission with your app.
60    /// Get yours at <https://anti-captcha.com/clients/tools/devcenter>.
61    pub fn with_soft_id(mut self, soft_id: i64) -> Self {
62        self.soft_id = soft_id;
63        self
64    }
65
66    /// Debug output goes to stderr. On by default.
67    pub fn with_verbose(mut self, verbose: bool) -> Self {
68        self.verbose = verbose;
69        self
70    }
71
72    /// Same as `with_verbose(false)`.
73    pub fn quiet(self) -> Self {
74        self.with_verbose(false)
75    }
76
77    /// Timeout of a single HTTP call to the API. Default 30 seconds.
78    pub fn with_connection_timeout(mut self, timeout: Duration) -> Self {
79        self.connection_timeout = timeout;
80        self
81    }
82
83    /// How long to wait before the first status request, and between the
84    /// following ones. Default 5 seconds each.
85    pub fn with_polling_intervals(mut self, first: Duration, normal: Duration) -> Self {
86        self.first_attempt_waiting_interval = first;
87        self.normal_waiting_interval = normal;
88        self
89    }
90
91    /// How long to keep polling before giving up. Default 300 seconds.
92    pub fn with_max_waiting_time(mut self, timeout: Duration) -> Self {
93        self.max_waiting_time = timeout;
94        self
95    }
96
97    fn log(&self, message: impl std::fmt::Display) {
98        if self.verbose {
99            eprintln!("[anticaptcha] {message}");
100        }
101    }
102
103    // ------------------------------------------------------------------ money
104
105    /// Account balance in US dollars.
106    pub async fn get_balance(&self) -> Result<f64> {
107        let response = self.json_request("getBalance", json!({})).await?;
108
109        Ok(response
110            .get("balance")
111            .and_then(Value::as_f64)
112            .unwrap_or_default())
113    }
114
115    /// Number of prepaid captcha credits on the account.
116    pub async fn get_credits_balance(&self) -> Result<f64> {
117        let response = self.json_request("getBalance", json!({})).await?;
118
119        Ok(response
120            .get("captchaCredits")
121            .and_then(Value::as_f64)
122            .unwrap_or_default())
123    }
124
125    // ------------------------------------------------------------- low level
126
127    /// Calls any API method with your own payload. The client key is added for you.
128    pub async fn json_request(&self, method: &str, mut payload: Value) -> Result<Value> {
129        if self.api_key.is_empty() {
130            return Err(Error::InvalidTask("API key is not set".into()));
131        }
132
133        if let Value::Object(fields) = &mut payload {
134            fields.insert("clientKey".into(), json!(self.api_key));
135        }
136
137        let url = format!("{API_HOST}{method}");
138        self.log(format_args!("POST {url}"));
139
140        let response = self
141            .http
142            .post(&url)
143            .timeout(self.connection_timeout)
144            .json(&payload)
145            .send()
146            .await?;
147
148        let status = response.status();
149        let raw = response.text().await?;
150
151        let body: Value = serde_json::from_str(&raw).map_err(|error| Error::BadResponse {
152            message: error.to_string(),
153            raw: raw.chars().take(500).collect(),
154        })?;
155
156        if !status.is_success() {
157            return Err(Error::BadResponse {
158                message: format!("API answered with HTTP {status}"),
159                raw: raw.chars().take(500).collect(),
160            });
161        }
162
163        let error_id = body.get("errorId").and_then(Value::as_i64).unwrap_or(-1);
164
165        if error_id != 0 {
166            return Err(Error::Api {
167                error_id,
168                error_code: body
169                    .get("errorCode")
170                    .and_then(Value::as_str)
171                    .unwrap_or_default()
172                    .to_owned(),
173                description: body
174                    .get("errorDescription")
175                    .and_then(Value::as_str)
176                    .unwrap_or("(no error description)")
177                    .to_owned(),
178            });
179        }
180
181        Ok(body)
182    }
183
184    /// Submits a task and returns its id.
185    pub async fn create_task(&self, task: Value) -> Result<i64> {
186        self.log(format_args!("Creating task: {task}"));
187
188        let response = self
189            .json_request(
190                "createTask",
191                json!({ "task": task, "softId": self.soft_id }),
192            )
193            .await?;
194
195        let task_id = response
196            .get("taskId")
197            .and_then(Value::as_i64)
198            .ok_or_else(|| Error::BadResponse {
199                message: "API did not return a task id".into(),
200                raw: response.to_string().chars().take(500).collect(),
201            })?;
202
203        self.log(format_args!("Task id: {task_id}"));
204
205        Ok(task_id)
206    }
207
208    /// Polls until the task is solved or the waiting limit runs out.
209    pub async fn wait_for_result(&self, task_id: i64) -> Result<Solution> {
210        let deadline = Instant::now() + self.max_waiting_time;
211        let mut interval = self.first_attempt_waiting_interval;
212
213        loop {
214            self.log(format_args!("Waiting {} seconds...", interval.as_secs()));
215            tokio::time::sleep(interval).await;
216            interval = self.normal_waiting_interval;
217
218            let response = self
219                .json_request("getTaskResult", json!({ "taskId": task_id }))
220                .await?;
221
222            let status = response
223                .get("status")
224                .and_then(Value::as_str)
225                .unwrap_or_default();
226
227            match status {
228                "ready" => {
229                    let cost = response
230                        .get("cost")
231                        .and_then(Value::as_f64)
232                        .unwrap_or_default();
233
234                    let solution = response
235                        .get("solution")
236                        .filter(|value| value.is_object())
237                        .ok_or_else(|| Error::BadResponse {
238                            message: "the task is ready but carries no solution".into(),
239                            raw: response.to_string().chars().take(500).collect(),
240                        })?;
241
242                    let solution = Solution::new(solution.clone());
243
244                    if solution.is_empty() {
245                        return Err(Error::BadResponse {
246                            message: "the API returned an empty solution".into(),
247                            raw: response.to_string().chars().take(500).collect(),
248                        });
249                    }
250
251                    self.log("The task is complete");
252
253                    return Ok(solution.with_task(task_id, cost));
254                }
255                "processing" => {
256                    if Instant::now() >= deadline {
257                        return Err(Error::Timeout(self.max_waiting_time.as_secs()));
258                    }
259
260                    self.log("The task is still processing...");
261                }
262                other => {
263                    return Err(Error::BadResponse {
264                        message: format!(
265                            "unknown task status \"{other}\", please update the library"
266                        ),
267                        raw: response.to_string().chars().take(500).collect(),
268                    })
269                }
270            }
271        }
272    }
273
274    /// Sends a task type this library does not wrap yet, and waits for the result.
275    /// See <https://anti-captcha.com/apidoc/task-types> for the `task` object shape.
276    pub async fn solve_task(&self, task: Value) -> Result<Solution> {
277        let task_id = self.create_task(task).await?;
278
279        self.wait_for_result(task_id).await
280    }
281
282    // ----------------------------------------------------------------- tasks
283
284    pub async fn solve_image(
285        &self,
286        base64_body: &str,
287        settings: &tasks::ImageSettings,
288    ) -> Result<Solution> {
289        self.solve_task(tasks::build_image(base64_body, settings)?)
290            .await
291    }
292
293    pub async fn solve_image_file(
294        &self,
295        path: impl AsRef<std::path::Path>,
296        settings: &tasks::ImageSettings,
297    ) -> Result<Solution> {
298        self.solve_image(&Self::file_to_base64(path)?, settings)
299            .await
300    }
301
302    pub async fn solve_image_to_coordinates(
303        &self,
304        base64_body: &str,
305        settings: &tasks::ImageToCoordinates,
306    ) -> Result<Solution> {
307        self.solve_task(tasks::build_image_to_coordinates(base64_body, settings)?)
308            .await
309    }
310
311    pub async fn solve_image_to_coordinates_file(
312        &self,
313        path: impl AsRef<std::path::Path>,
314        settings: &tasks::ImageToCoordinates,
315    ) -> Result<Solution> {
316        self.solve_image_to_coordinates(&Self::file_to_base64(path)?, settings)
317            .await
318    }
319
320    pub async fn solve_recaptcha_v2(&self, settings: &tasks::RecaptchaV2) -> Result<Solution> {
321        self.solve_task(tasks::build_recaptcha_v2(settings, false)?)
322            .await
323    }
324
325    pub async fn solve_recaptcha_v2_proxy_on(
326        &self,
327        settings: &tasks::RecaptchaV2,
328    ) -> Result<Solution> {
329        self.solve_task(tasks::build_recaptcha_v2(settings, true)?)
330            .await
331    }
332
333    pub async fn solve_recaptcha_v3(&self, settings: &tasks::RecaptchaV3) -> Result<Solution> {
334        self.solve_task(tasks::build_recaptcha_v3(settings)?).await
335    }
336
337    pub async fn solve_hcaptcha(&self, settings: &tasks::HCaptcha) -> Result<Solution> {
338        self.solve_task(tasks::build_hcaptcha(settings, false)?)
339            .await
340    }
341
342    pub async fn solve_hcaptcha_proxy_on(&self, settings: &tasks::HCaptcha) -> Result<Solution> {
343        self.solve_task(tasks::build_hcaptcha(settings, true)?)
344            .await
345    }
346
347    pub async fn solve_funcaptcha(&self, settings: &tasks::FunCaptcha) -> Result<Solution> {
348        self.solve_task(tasks::build_funcaptcha(settings, false)?)
349            .await
350    }
351
352    pub async fn solve_funcaptcha_proxy_on(
353        &self,
354        settings: &tasks::FunCaptcha,
355    ) -> Result<Solution> {
356        self.solve_task(tasks::build_funcaptcha(settings, true)?)
357            .await
358    }
359
360    pub async fn solve_geetest(&self, settings: &tasks::GeeTest) -> Result<Solution> {
361        self.solve_task(tasks::build_geetest(settings, false)?)
362            .await
363    }
364
365    pub async fn solve_geetest_proxy_on(&self, settings: &tasks::GeeTest) -> Result<Solution> {
366        self.solve_task(tasks::build_geetest(settings, true)?).await
367    }
368
369    pub async fn solve_turnstile(&self, settings: &tasks::Turnstile) -> Result<Solution> {
370        self.solve_task(tasks::build_turnstile(settings, false)?)
371            .await
372    }
373
374    pub async fn solve_turnstile_proxy_on(&self, settings: &tasks::Turnstile) -> Result<Solution> {
375        self.solve_task(tasks::build_turnstile(settings, true)?)
376            .await
377    }
378
379    pub async fn solve_prosopo(&self, settings: &tasks::Prosopo) -> Result<Solution> {
380        self.solve_task(tasks::build_prosopo(settings, false)?)
381            .await
382    }
383
384    pub async fn solve_prosopo_proxy_on(&self, settings: &tasks::Prosopo) -> Result<Solution> {
385        self.solve_task(tasks::build_prosopo(settings, true)?).await
386    }
387
388    pub async fn solve_friendly_captcha(
389        &self,
390        settings: &tasks::FriendlyCaptcha,
391    ) -> Result<Solution> {
392        self.solve_task(tasks::build_friendly_captcha(settings, false)?)
393            .await
394    }
395
396    pub async fn solve_friendly_captcha_proxy_on(
397        &self,
398        settings: &tasks::FriendlyCaptcha,
399    ) -> Result<Solution> {
400        self.solve_task(tasks::build_friendly_captcha(settings, true)?)
401            .await
402    }
403
404    pub async fn solve_altcha(&self, settings: &tasks::Altcha) -> Result<Solution> {
405        self.solve_task(tasks::build_altcha(settings, false)?).await
406    }
407
408    pub async fn solve_altcha_proxy_on(&self, settings: &tasks::Altcha) -> Result<Solution> {
409        self.solve_task(tasks::build_altcha(settings, true)?).await
410    }
411
412    pub async fn solve_amazon(&self, settings: &tasks::Amazon) -> Result<Solution> {
413        self.solve_task(tasks::build_amazon(settings, false)?).await
414    }
415
416    pub async fn solve_amazon_proxy_on(&self, settings: &tasks::Amazon) -> Result<Solution> {
417        self.solve_task(tasks::build_amazon(settings, true)?).await
418    }
419
420    pub async fn solve_antigate(&self, settings: &tasks::AntiGate) -> Result<Solution> {
421        self.solve_task(tasks::build_antigate(settings)?).await
422    }
423
424    pub async fn solve_antibot_cookie(&self, settings: &tasks::AntiBotCookie) -> Result<Solution> {
425        self.solve_task(tasks::build_antibot_cookie(settings)?)
426            .await
427    }
428
429    // --------------------------------------------------------------- reports
430
431    /// Reports an image captcha as answered incorrectly.
432    pub async fn report_incorrect_image_captcha(&self, task_id: i64) -> Result<()> {
433        self.report("reportIncorrectImageCaptcha", task_id).await
434    }
435
436    pub async fn report_incorrect_recaptcha(&self, task_id: i64) -> Result<()> {
437        self.report("reportIncorrectRecaptcha", task_id).await
438    }
439
440    pub async fn report_correct_recaptcha(&self, task_id: i64) -> Result<()> {
441        self.report("reportCorrectRecaptcha", task_id).await
442    }
443
444    pub async fn report_incorrect_hcaptcha(&self, task_id: i64) -> Result<()> {
445        self.report("reportIncorrectHcaptcha", task_id).await
446    }
447
448    async fn report(&self, method: &str, task_id: i64) -> Result<()> {
449        self.json_request(method, json!({ "taskId": task_id }))
450            .await?;
451
452        Ok(())
453    }
454
455    // --------------------------------------------------------------- helpers
456
457    /// Reads a file and encodes it in base64.
458    pub fn file_to_base64(path: impl AsRef<std::path::Path>) -> Result<String> {
459        let path = path.as_ref();
460
461        let bytes = std::fs::read(path).map_err(|source| Error::Io {
462            path: path.display().to_string(),
463            source,
464        })?;
465
466        Ok(BASE64.encode(bytes))
467    }
468
469    /// Encodes bytes in base64.
470    pub fn to_base64(bytes: impl AsRef<[u8]>) -> String {
471        BASE64.encode(bytes)
472    }
473}
474
475#[cfg(test)]
476mod tests {
477    use super::*;
478
479    #[test]
480    fn base64_matches_the_reference_vectors() {
481        // RFC 4648 test vectors
482        assert_eq!(Client::to_base64(""), "");
483        assert_eq!(Client::to_base64("f"), "Zg==");
484        assert_eq!(Client::to_base64("fo"), "Zm8=");
485        assert_eq!(Client::to_base64("foo"), "Zm9v");
486        assert_eq!(Client::to_base64("foob"), "Zm9vYg==");
487        assert_eq!(Client::to_base64("fooba"), "Zm9vYmE=");
488        assert_eq!(Client::to_base64("foobar"), "Zm9vYmFy");
489        // bytes above 0x7F must not be mangled
490        assert_eq!(Client::to_base64([0xFFu8, 0xFE, 0xFD]), "//79");
491    }
492
493    #[test]
494    fn missing_file_is_an_io_error() {
495        let error = Client::file_to_base64("/definitely/not/here.jpg").unwrap_err();
496
497        assert!(matches!(error, Error::Io { .. }));
498    }
499
500    #[tokio::test]
501    async fn empty_api_key_is_refused_before_any_request() {
502        let client = Client::new("").quiet();
503        let error = client.get_balance().await.unwrap_err();
504
505        assert!(matches!(error, Error::InvalidTask(_)));
506    }
507
508    #[test]
509    fn builder_settings_stick() {
510        let client = Client::new("KEY")
511            .with_soft_id(1187)
512            .quiet()
513            .with_max_waiting_time(Duration::from_secs(60));
514
515        assert_eq!(client.soft_id, 1187);
516        assert!(!client.verbose);
517        assert_eq!(client.max_waiting_time, Duration::from_secs(60));
518    }
519}