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
76
77
78
79
80
81
82
83
84
85
86
87
88
use reqwest::Client;

use crate::{
    connection::{ConnectionGraphResponse, ResponseConnections},
    login::try_get_access_token,
};

pub struct LibreLinkClient {
    client: Client,
    token: String,
    base_url: String,
}

pub struct Credentials {
    pub username: String,
    pub password: String,
}

impl LibreLinkClient {
    pub async fn new(credentials: Credentials) -> Result<Self, Box<dyn std::error::Error>> {
        let token = try_get_access_token(&credentials.username, &credentials.password).await;

        match token {
            Ok(token) => Ok(LibreLinkClient {
                client: Client::new(),
                token: token,
                base_url: "https://api.libreview.io".to_string(),
            }),
            Err(e) => Err(e),
        }
    }

    pub fn from_token(token: String) -> Self {
        LibreLinkClient {
            client: Client::new(),
            token: token,
            base_url: "https://api.libreview.io".to_string(),
        }
    }

    pub async fn get_connections(&self) -> Result<ResponseConnections, Box<dyn std::error::Error>> {
        let url = format!("{}/{}", &self.base_url, "llu/connections");

        let response = self
            .client
            .get(url)
            .header("version", "4.7.1")
            .header("product", "llu.android")
            .header("User-Agent", "Apidog/1.0.0 (https://apidog.com)")
            .bearer_auth(&self.token)
            .send()
            .await?;

        let api_response: Result<ResponseConnections, reqwest::Error> = response.json().await;

        match api_response {
            Ok(response_data) => Ok(response_data),
            Err(e) => Err(Box::new(e)),
        }
    }

    pub async fn get_connection_graph(
        &self,
        connection_id: &str,
    ) -> Result<ConnectionGraphResponse, Box<dyn std::error::Error>> {
        let url = format!(
            "{}/{}/{}/{}",
            &self.base_url, "llu/connections", connection_id, "graph"
        );

        let response = self
            .client
            .get(url)
            .header("version", "4.7.1")
            .header("product", "llu.android")
            .header("User-Agent", "Apidog/1.0.0 (https://apidog.com)")
            .bearer_auth(&self.token)
            .send()
            .await?;

        let api_response: Result<ConnectionGraphResponse, reqwest::Error> = response.json().await;

        match api_response {
            Ok(response_data) => Ok(response_data),
            Err(e) => Err(Box::new(e)),
        }
    }
}