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
use reqwest::{
    blocking::Client,
};

use crate::*;

///SnClient represents a connection with the Schoolloop API and is the main point of interaction for this library
pub struct SnClient {
    client: Client
}

impl SnClient {
    ///Creates a new Client
    pub fn new() -> SnClient {
        SnClient {
            client: Client::new(),
        }
    }

    ///Sends login details to the Schoolloop Api, and returns a User upon success.
    ///Err result indicates that user has incorrect credentials
    pub fn login(&self, login: Login) -> Result<User, SnError> {
        let url = format!("{}/mapi/login?version=3", login.get_base_url());
        let data = login.add_login(self.client.get(&url))
            .send()?;
        match data.json::<UserDataJSON>() {
            Ok(d) => {
                Ok(User::new(login, d.to_user_data()?))
            },
            Err(e) => {
                Err(e.into())
            }
        }
    }

    ///Gets the classes of a user
    ///Returns Err if User was not created correctly, and could not fetch from API
    pub fn get_classes(&self, user: &User) -> Result<Classes, SnError> {
        let url = format!("{}/mapi/report_card?studentID={}", 
            user.login.get_base_url(), user.data.id
        );
        let data = user.login.add_login(self.client.get(&url))
            .send()?;
        match data.json::<Vec<ClassJSON>>() {
            Ok(d) => {
                let classes = d
                    .iter()
                    .map(|c| c.clone().to_class())
                    .collect::<Result<Vec<Class>, SnError>>()?;
                Ok(Classes::new(classes))
            },
            Err(e) => {
                Err(e.into())
            }
        }
    }
}