Skip to main content

twikit/
captcha.rs

1//! Captcha solver interfaces.
2
3use regex::Regex;
4use serde_json::{json, Value};
5use tokio::time::{sleep, Duration};
6
7use crate::client::{Client, RequestBody};
8use crate::constants::DOMAIN;
9use crate::error::{Error, Result};
10
11/// Parsed unlock HTML.
12#[derive(Debug, Clone, Default)]
13pub struct UnlockHTML {
14    /// Authenticity token.
15    pub authenticity_token: Option<String>,
16    /// Assignment token.
17    pub assignment_token: Option<String>,
18    /// Needs unlock.
19    pub needs_unlock: bool,
20    /// Start button present.
21    pub start_button: bool,
22    /// Finish button present.
23    pub finish_button: bool,
24    /// Delete button present.
25    pub delete_button: bool,
26    /// Arkose blob.
27    pub blob: Option<String>,
28}
29
30/// Captcha solver trait object replacement.
31#[derive(Debug, Clone, Default)]
32pub struct CaptchaSolver {
33    /// Maximum attempts.
34    pub max_attempts: usize,
35    /// Optional client used by Python-style no-argument methods.
36    pub client: Option<Client>,
37}
38
39impl CaptchaSolver {
40    /// Create a base captcha solver.
41    pub fn new(max_attempts: usize) -> Self {
42        Self {
43            max_attempts,
44            client: None,
45        }
46    }
47
48    /// Attach a client so Python-style no-argument methods can perform IO.
49    pub fn with_client(mut self, client: Client) -> Self {
50        self.client = Some(client);
51        self
52    }
53
54    /// Get unlock HTML.
55    pub async fn get_unlock_html(&self) -> Result<UnlockHTML> {
56        let client = self.client()?;
57        self.get_unlock_html_for(client).await
58    }
59
60    /// UI metrics.
61    pub async fn ui_metrix(&self) -> Result<String> {
62        self.client()?._ui_metrics().await
63    }
64
65    /// Confirm unlock.
66    pub async fn confirm_unlock(&self) -> Result<UnlockHTML> {
67        let client = self.client()?;
68        let html = self.get_unlock_html_for(client).await?;
69        self.confirm_unlock_for(client, &html, None, true).await
70    }
71
72    /// Fetch and parse account unlock HTML for an explicit client.
73    pub async fn get_unlock_html_for(&self, client: &Client) -> Result<UnlockHTML> {
74        get_unlock_html_for_client(client).await
75    }
76
77    /// Confirm one unlock step for an explicit client.
78    pub async fn confirm_unlock_for(
79        &self,
80        client: &Client,
81        html: &UnlockHTML,
82        verification_string: Option<&str>,
83        ui_metrics: bool,
84    ) -> Result<UnlockHTML> {
85        confirm_unlock_for_client(client, html, verification_string, ui_metrics).await
86    }
87
88    fn client(&self) -> Result<&Client> {
89        self.client
90            .as_ref()
91            .ok_or_else(|| Error::Interactive("CaptchaSolver has no attached Client".into()))
92    }
93}
94
95/// Capsolver client.
96#[derive(Debug, Clone)]
97pub struct Capsolver {
98    /// API key.
99    pub api_key: String,
100    /// Max attempts.
101    pub max_attempts: usize,
102    /// Poll interval seconds.
103    pub get_result_interval: f64,
104    /// Whether blob data is sent.
105    pub use_blob_data: bool,
106}
107
108impl Capsolver {
109    /// Maximum unlock attempts, defaulting to Python twikit's 3 when unset.
110    pub fn attempts(&self) -> usize {
111        self.max_attempts.max(3)
112    }
113
114    /// Fetch and parse account unlock HTML.
115    pub async fn get_unlock_html_for(&self, client: &Client) -> Result<UnlockHTML> {
116        get_unlock_html_for_client(client).await
117    }
118
119    /// Confirm one unlock step.
120    pub async fn confirm_unlock_for(
121        &self,
122        client: &Client,
123        html: &UnlockHTML,
124        verification_string: Option<&str>,
125        ui_metrics: bool,
126    ) -> Result<UnlockHTML> {
127        confirm_unlock_for_client(client, html, verification_string, ui_metrics).await
128    }
129
130    /// Fetch account-access ui_metrics object.
131    pub async fn ui_metrix_for(&self, client: &Client) -> Result<String> {
132        client._ui_metrics().await
133    }
134
135    /// Create task.
136    pub async fn create_task(&self, task_data: Value) -> Result<Value> {
137        Ok(reqwest::Client::new()
138            .post(format!("{}/createTask", capsolver_url()))
139            .header(reqwest::header::CONTENT_TYPE, "application/json")
140            .json(&json!({"clientKey": self.api_key, "task": task_data}))
141            .send()
142            .await?
143            .json()
144            .await?)
145    }
146
147    /// Get task result.
148    pub async fn get_task_result(&self, task_id: &str) -> Result<Value> {
149        Ok(reqwest::Client::new()
150            .post(format!("{}/getTaskResult", capsolver_url()))
151            .header(reqwest::header::CONTENT_TYPE, "application/json")
152            .json(&json!({"clientKey": self.api_key, "taskId": task_id}))
153            .send()
154            .await?
155            .json()
156            .await?)
157    }
158
159    /// Solve funcaptcha.
160    pub async fn solve_funcaptcha(&self, blob: &str) -> Result<Value> {
161        let mut task = json!({
162            "type": "FunCaptchaTaskProxyLess",
163            "websiteURL": "https://iframe.arkoselabs.com",
164            "websitePublicKey": "0152B4EB-D2DC-460A-89A1-629838B529C9",
165            "funcaptchaApiJSSubdomain": "https://client-api.arkoselabs.com"
166        });
167        if self.use_blob_data {
168            task["data"] = json!(format!(r#"{{"blob":"{blob}"}}"#));
169        }
170        let created = self.create_task(task).await?;
171        let task_id = created
172            .get("taskId")
173            .and_then(Value::as_str)
174            .ok_or(Error::Missing("taskId"))?;
175
176        loop {
177            sleep(Duration::from_secs_f64(self.get_result_interval.max(0.0))).await;
178            let result = self.get_task_result(task_id).await?;
179            match result.get("status").and_then(Value::as_str) {
180                Some("ready") | Some("failed") => return Ok(result),
181                _ => {}
182            }
183        }
184    }
185}
186
187async fn get_unlock_html_for_client(client: &Client) -> Result<UnlockHTML> {
188    let url = captcha_url();
189    let mut headers = client.base_headers();
190    headers.insert(
191        "Upgrade-Insecure-Requests",
192        "1".parse().expect("valid header"),
193    );
194    let response = client
195        .request_raw(reqwest::Method::GET, url, Some(headers), None, None, true)
196        .await?;
197    let html = response.as_str().unwrap_or("").to_string();
198    parse_unlock_html(&html)
199}
200
201async fn confirm_unlock_for_client(
202    client: &Client,
203    html: &UnlockHTML,
204    verification_string: Option<&str>,
205    ui_metrics: bool,
206) -> Result<UnlockHTML> {
207    let authenticity_token = html
208        .authenticity_token
209        .as_deref()
210        .ok_or(Error::Missing("authenticity_token"))?;
211    let assignment_token = html
212        .assignment_token
213        .as_deref()
214        .ok_or(Error::Missing("assignment_token"))?;
215
216    let mut form = vec![
217        ("authenticity_token".into(), authenticity_token.into()),
218        ("assignment_token".into(), assignment_token.into()),
219        ("lang".into(), "en".into()),
220        ("flow".into(), String::new()),
221    ];
222    let mut params = Vec::new();
223    if let Some(value) = verification_string {
224        form.push(("verification_string".into(), value.into()));
225        form.push(("language_code".into(), "en".into()));
226        params.push(("lang".into(), "en".into()));
227    }
228    if ui_metrics {
229        form.push(("ui_metrics".into(), client._ui_metrics().await?));
230    }
231
232    let mut headers = client.base_headers();
233    headers.insert(
234        reqwest::header::CONTENT_TYPE,
235        "application/x-www-form-urlencoded"
236            .parse()
237            .expect("valid header"),
238    );
239    headers.insert(
240        "Upgrade-Insecure-Requests",
241        "1".parse().expect("valid header"),
242    );
243    headers.insert("Referer", captcha_url().parse().expect("valid header"));
244
245    let response = client
246        .request_raw(
247            reqwest::Method::POST,
248            captcha_url(),
249            Some(headers),
250            if params.is_empty() {
251                None
252            } else {
253                Some(params)
254            },
255            Some(RequestBody::Form(form)),
256            true,
257        )
258        .await?;
259    let html = response.as_str().unwrap_or("").to_string();
260    parse_unlock_html(&html)
261}
262
263fn captcha_url() -> String {
264    if let Ok(base) = std::env::var("TWIKIT_RS_WEB_BASE") {
265        return format!("{}/account/access", base.trim_end_matches('/'));
266    }
267    format!("https://{DOMAIN}/account/access")
268}
269
270fn capsolver_url() -> String {
271    std::env::var("TWIKIT_RS_CAPSOLVER_BASE")
272        .unwrap_or_else(|_| "https://api.capsolver.com".to_string())
273        .trim_end_matches('/')
274        .to_string()
275}
276
277/// Parse account unlock HTML into the fields required by unlock flow.
278pub fn parse_unlock_html(html: &str) -> Result<UnlockHTML> {
279    Ok(UnlockHTML {
280        authenticity_token: input_value(html, "authenticity_token"),
281        assignment_token: input_value(html, "assignment_token"),
282        needs_unlock: html.contains("id=\"verification_string\"")
283            || html.contains("id='verification_string'"),
284        start_button: input_value_present(html, "Start"),
285        finish_button: input_value_present(html, "Continue to X"),
286        delete_button: input_value_present(html, "Delete"),
287        blob: arkose_blob(html),
288    })
289}
290
291fn input_value(html: &str, name: &str) -> Option<String> {
292    let pattern = format!(
293        r#"(?is)<input\b[^>]*\bname=["']{}["'][^>]*\bvalue=["']([^"']*)["'][^>]*>"#,
294        regex::escape(name)
295    );
296    Regex::new(&pattern)
297        .ok()?
298        .captures(html)
299        .and_then(|captures| captures.get(1))
300        .map(|value| value.as_str().to_string())
301}
302
303fn input_value_present(html: &str, value: &str) -> bool {
304    let pattern = format!(
305        r#"(?is)<input\b[^>]*\bvalue=["']{}["'][^>]*>"#,
306        regex::escape(value)
307    );
308    Regex::new(&pattern)
309        .map(|regex| regex.is_match(html))
310        .unwrap_or(false)
311}
312
313fn arkose_blob(html: &str) -> Option<String> {
314    let iframe = Regex::new(r#"(?is)<iframe\b[^>]*\bid=["']arkose_iframe["'][^>]*>"#)
315        .ok()?
316        .find(html)?
317        .as_str()
318        .to_string();
319    let src = Regex::new(r#"\bsrc=["']([^"']+)["']"#)
320        .ok()?
321        .captures(&iframe)
322        .and_then(|captures| captures.get(1))?
323        .as_str()
324        .to_string();
325    src.split("data=").nth(1).map(ToOwned::to_owned)
326}