1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Debug)]
pub struct ResponseLoginRequest {
    pub status: i32,
    pub data: Data,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct Data {
    #[serde(rename = "authTicket")]
    pub auth_ticket: AuthTicket,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct AuthTicket {
    pub token: String,
    expires: u64,
    duration: u64,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct ErrorResponse {
    pub status: i32,
    pub error: Error,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct Error {
    pub message: String,
}

pub async fn try_get_access_token(
    username: &str,
    password: &str,
) -> Result<String, Box<dyn std::error::Error>> {
    let url = "https://api.libreview.io/llu/auth/login";

    let login_request = serde_json::json!({
        "email": username,
        "password": password,
    });

    let client = reqwest::Client::new();

    let response = client
        .post(url)
        .header("version", "4.2.1")
        .header("product", "llu.android")
        .header("User-Agent", "Apidog/1.0.0 (https://apidog.com)")
        .json(&login_request)
        .send()
        .await?;

    let text = response.text().await?;
    let api_response: Result<ResponseLoginRequest, serde_json::Error> = serde_json::from_str(&text);

    match api_response {
        Ok(response_data) => Ok(response_data.data.auth_ticket.token),
        Err(_) => {
            let error_response: ErrorResponse = serde_json::from_str(&text).unwrap();
            if error_response.status == 2 {
                Err(Box::new(std::io::Error::new(
                    std::io::ErrorKind::Other,
                    error_response.error.message,
                )))
            } else {
                Err(Box::new(std::io::Error::new(
                    std::io::ErrorKind::Other,
                    "Unknown error",
                )))
            }
        }
    }
}