Skip to main content

leetcode_core/
lib.rs

1pub mod errors;
2pub mod graphql;
3pub mod types;
4use errors::AppResult;
5pub use graphql::client::GQLLeetcodeRequest;
6pub use graphql::query::problemset_question_list::Query as QuestionRequest;
7pub use graphql::query::question_content::Query as QuestionContentRequest;
8pub use graphql::query::run_code::RunCodeRequest;
9pub use graphql::query::submit_code::SubmitCodeRequest;
10pub use graphql::query::EditorDataRequest;
11pub use reqwest::header::{HeaderMap, HeaderValue};
12pub use reqwest::Client;
13use std::sync::OnceLock;
14use std::time::Duration;
15pub use types::editor_data::QuestionData as EditorDataResponse;
16pub use types::problemset_question_list::Root as QuestionResponse;
17pub use types::rest_problems_all::ProblemsAllResponse;
18
19pub static REQ_CLIENT: OnceLock<reqwest::Client> = OnceLock::new();
20
21pub async fn init(csrf: &str, sess: &str) -> AppResult<()> {
22    let client = build_reqwest_client(csrf, sess).await?;
23    REQ_CLIENT.get_or_init(|| client);
24    Ok(())
25}
26
27pub(crate) fn get_client() -> &'static Client {
28    REQ_CLIENT.get().expect("Client not initialized")
29}
30
31pub async fn build_reqwest_client(csrf: &str, sess: &str) -> AppResult<Client> {
32    let mut headers = HeaderMap::new();
33    let header_k_v = [
34        (
35            "Cookie",
36            format!("LEETCODE_SESSION={sess}; csrftoken={csrf}"),
37        ),
38        ("Content-Type", "application/json".to_string()),
39        ("x-csrftoken", csrf.to_string()),
40        ("Origin", "https://leetcode.com".to_string()),
41        ("Referer", "https://leetcode.com".to_string()),
42        ("Connection", "keep-alive".to_string()),
43    ];
44
45    for (key, value) in header_k_v {
46        headers.append(key, HeaderValue::from_str(value.as_str())?);
47    }
48
49    let client = reqwest::ClientBuilder::new()
50        .default_headers(headers)
51        .timeout(Duration::from_secs(30))
52        .connect_timeout(Duration::from_secs(10))
53        .build()?;
54    Ok(client)
55}
56
57pub async fn fetch_all_problems_rest() -> AppResult<ProblemsAllResponse> {
58    let response = get_client()
59        .get("https://leetcode.com/api/problems/all")
60        .send()
61        .await?;
62
63    if response.status().as_u16() == 403 {
64        return Err(errors::LcAppError::CookiesExpiredError);
65    } else if response.status().as_u16() != 200 {
66        return Err(errors::LcAppError::StatusCodeError {
67            code: response.status().to_string(),
68            contents: response.text().await?,
69        });
70    }
71
72    let result = response.text().await?;
73    let parsed: ProblemsAllResponse = serde_json::from_str(&result)?;
74    Ok(parsed)
75}