lanis-rs 0.2.0

A API for Lanis (Schulportal Hessen)
Documentation
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
use crate::base::account::AccountType::{Student, Teacher};
use crate::base::schools::{get_school, get_schools, School};
use crate::utils::constants::URL;
use crate::utils::crypt::{
    decrypt_any, encrypt_any, generate_lanis_key_pair, CryptorError, LanisKeyPair,
};
use crate::utils::datetime::date_string_to_naivedate;
use crate::Error;
use crate::Feature;
use chrono::NaiveDate;
use reqwest::header::LOCATION;
use reqwest::redirect::Policy;
use reqwest::{Client, StatusCode};
use reqwest_cookie_store::{CookieStore, CookieStoreMutex};
use scraper::{Html, Selector};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::fmt::Display;
use std::string::String;
use std::sync::Arc;

#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Serialize, Deserialize)]
pub enum AccountType {
    Student,
    Teacher,
    Parent,
    Unknown,
}

impl Display for AccountType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Student => write!(f, "Student"),
            Teacher => write!(f, "Teacher"),
            AccountType::Parent => write!(f, "Parent"),
            AccountType::Unknown => write!(f, "Unknown"),
        }
    }
}

/// Stores everything that is needed at Runtime and related to the Account
#[derive(Clone, Debug)]
pub struct Account {
    pub school: School,
    pub secrets: AccountSecrets,
    pub account_type: AccountType,
    pub features: Vec<Feature>,
    // If you used `Account::new` this is guranteed to be `Some`
    pub info: Option<AccountInfo>,
    /// You can generate a new KeyPair by using the Ok result of [generate_lanis_key_pair()] <br> Make sure to not define anything larger than 151 (bits) as size
    pub key_pair: LanisKeyPair,
    pub client: Client,
    pub cookie_store: Arc<CookieStoreMutex>,
}

/// The account info
/// Some fields may be empty if the value doesn't exist in the SPH
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
pub struct AccountInfo {
    pub firstname: String,
    pub lastname: String,
    pub username: String,
    pub birthdate: NaiveDate,
    pub gender: Gender,
    pub grade: String,
    pub class: String,
}

#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Serialize, Deserialize)]
pub enum Gender {
    Male,
    Female,
    Diverse,
    Unknown,
}

impl Account {
    /// Creates a new [Account] from a school_id, username and password <br>
    /// When using [new] a session gets automatically created and all fields will be set
    pub async fn new(secrets: AccountSecrets) -> Result<Account, Error> {
        let cookie_store = CookieStore::new(None);
        let cookie_store = CookieStoreMutex::new(cookie_store);
        let cookie_store = Arc::new(cookie_store);

        let client = Client::builder()
            .redirect(Policy::none())
            .cookie_provider(std::sync::Arc::clone(&cookie_store))
            .gzip(true)
            .build()
            .unwrap();

        let key_pair = generate_lanis_key_pair(128, &client).await?;

        let schools = get_schools(&client).await?;
        let school = get_school(&secrets.school_id, &schools).await?;

        let mut account = Account {
            school,
            secrets,
            account_type: AccountType::Unknown,
            info: None,
            features: Vec::new(),
            key_pair,
            client,
            cookie_store,
        };

        account.create_session().await?;
        account.info = Some(account.fetch_account_info().await?);
        account.account_type = account.get_type().await;
        account.features = account.get_features().await?;

        Ok(account)
    }

    /**
     * Takes an account and a 'reqwest' client and generates a new session for lanis <br>
     * Needs to be run on every new 'reqwest' client <br>
     * Doesn't need to be run if [new] was used
     */
    pub async fn create_session(&self) -> Result<(), Error> {
        let params = [
            ("user2", self.secrets.username.clone()),
            (
                "user",
                format!("{}.{}", self.school.id, self.secrets.username.clone()),
            ),
            ("password", self.secrets.password.clone()),
        ];
        let response = self
            .client
            .post(URL::LOGIN.to_owned() + &*format!("?i={}", self.school.id))
            .form(&params)
            .send();
        match response.await {
            Ok(response) => {
                let response_status = response.status();

                let text = response.text().await.map_err(|e| {
                    Error::Parsing(format!("Failed to parse response as text: {}", e))
                })?;
                let html = Html::parse_document(&text);

                let timeout_selector = Selector::parse("#authErrorLocktime").unwrap();
                if let Some(timeout) = html.select(&timeout_selector).nth(0) {
                    return Err(Error::LoginTimeout(
                        timeout
                            .text()
                            .collect::<String>()
                            .trim()
                            .parse()
                            .map_err(|e| {
                                Error::Parsing(format!(
                                    "Failed to parse timeout from response as u32: {}",
                                    e
                                ))
                            })?,
                    ));
                }

                if response_status == StatusCode::FOUND {
                    match self.client.get(URL::CONNECT).send().await {
                        Ok(response) => match response.headers().get(LOCATION) {
                            Some(location) => {
                                let location = location.to_str();
                                if location.is_err() {
                                    return Err(Error::Parsing(
                                        "failed to parse location header to str".to_string(),
                                    ));
                                }
                                let location = location.unwrap();

                                match self.client.get(location).send().await {
                                    Ok(_) => Ok(()),
                                    Err(e) => Err(Error::Network(format!(
                                        "error getting login URL header: {}",
                                        e
                                    ))),
                                }
                            }
                            None => Err(Error::Network("error getting login URL".to_string())),
                        },
                        Err(e) => Err(Error::Network(format!("{}", e))),
                    }
                } else {
                    Err(Error::Credentials("Wrong credentials!".to_string()))
                }
            }
            Err(e) => Err(Error::Network(e.to_string())),
        }
    }

    /**
     *  Refreshes the session to prevent getting logged out
     *  <br> Needs to be called periodically e.g. every 10 seconds
     */
    pub async fn prevent_logout(&self) -> Result<(), Error> {
        let sid: String = {
            let cs = self.cookie_store.lock().unwrap();
            let mut result = "NONE".to_string();
            for cookie in cs.iter_any() {
                if cookie.name() == "sid" {
                    result = cookie.value().to_string();
                }
            }
            result
        };
        let param = [("name", sid)];
        match self.client.get(URL::LOGIN_AJAX).form(&param).send().await {
            Ok(_) => Ok(()),
            Err(e) => Err(Error::Network(
                format!("failed to refresh session: {}", e).to_string(),
            )),
        }
    }

    pub async fn fetch_account_info(&self) -> Result<AccountInfo, Error> {
        match self
            .client
            .get(URL::USER_DATA)
            .query(&[("a", "userData")])
            .send()
            .await
        {
            Ok(response) => {
                let document = Html::parse_document(&response.text().await.unwrap());
                let user_data_table_body_selector =
                    Selector::parse("div.col-md-12 table.table.table-striped tbody").unwrap();

                let row_selector = Selector::parse("tr").unwrap();
                let key_selector = Selector::parse("td").unwrap();

                let mut result = BTreeMap::new();

                if let Some(user_data_table_body) =
                    document.select(&user_data_table_body_selector).next()
                {
                    for row in user_data_table_body.select(&row_selector) {
                        let cells: Vec<_> = row.select(&key_selector).collect();
                        if cells.len() >= 2 {
                            let key = cells[0].text().collect::<String>().trim().to_string();
                            let value = cells[1].text().collect::<String>().trim().to_string();
                            let key = key[..key.len() - 1].to_lowercase();
                            result.insert(key, value);
                        }
                    }
                }

                let firstname = result.get("vorname").unwrap_or(&String::new()).to_owned();
                let lastname = result.get("nachname").unwrap_or(&String::new()).to_owned();
                let username = result.get("login").unwrap_or(&String::new()).to_owned();
                let birthdate = {
                    let s = result
                        .get("geburtsdatum")
                        .unwrap_or(&String::from("01.01.1970"))
                        .to_owned();
                    date_string_to_naivedate(&s).map_err(|e| {
                        Error::DateTime(format!("failed to convert date to DateTime '{:?}'", e))
                    })?
                };
                let gender = {
                    let s = result
                        .get("geschlecht")
                        .unwrap_or(&String::new())
                        .to_owned();
                    match s.as_str() {
                        "männlich" => Gender::Male,
                        "weiblich" => Gender::Female,
                        "divers" => Gender::Diverse,
                        _ => Gender::Unknown,
                    }
                };
                let grade = result.get("stufe").unwrap_or(&String::new()).to_owned();
                let class = result.get("klasse").unwrap_or(&String::new()).to_owned();

                let info = AccountInfo {
                    firstname,
                    lastname,
                    username,
                    birthdate,
                    gender,
                    grade,
                    class,
                };

                Ok(info)
            }
            Err(e) => Err(Error::Network(
                format!("failed to fetch account data: {}", e).to_string(),
            )),
        }
    }

    pub async fn get_type(&self) -> AccountType {
        if !self.info.clone().unwrap().class.is_empty() {
            Student
        } else {
            Teacher
        }
    }

    /// Returns a vector of supported features (for the [Account])
    pub async fn get_features(&self) -> Result<Vec<Feature>, Error> {
        #[derive(Debug, Deserialize)]
        #[serde(rename_all = "lowercase")]
        struct Entry {
            link: String,
        }

        #[derive(Debug, Deserialize)]
        #[serde(rename_all = "lowercase")]
        struct Entries {
            entrys: Vec<Entry>,
        }

        match self
            .client
            .get(URL::START)
            .query(&[("a", "ajax"), ("f", "apps")])
            .send()
            .await
        {
            Ok(response) => {
                let text = response.text().await.unwrap();
                let entries = serde_json::from_str::<Entries>(&text).unwrap();

                let mut features = Vec::new();

                for entry in entries.entrys {
                    match entry.link.trim() {
                        "meinunterricht.php" => features.push(Feature::MeinUnttericht),
                        "stundenplan.php" => features.push(Feature::LanisTimetable),
                        "dateispeicher.php" => features.push(Feature::FileStorage),
                        "nachrichten.php" => features.push(Feature::MessagesBeta),
                        "kalender.php" => features.push(Feature::Calendar),
                        _ => continue,
                    }
                }

                Ok(features)
            }
            Err(e) => Err(Error::Network(e.to_string())),
        }
    }

    pub fn is_supported(&self, feature: Feature) -> bool {
        if self.features.contains(&feature) {
            true
        } else {
            false
        }
    }
}

/// Contains the account secrets for Lanis and maybe Untis <br>
/// This will be used for re-login. <br>
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Serialize, Deserialize)]
pub struct AccountSecrets {
    pub school_id: i32,
    pub username: String,
    pub password: String,
    pub untis_secrets: Option<UntisSecrets>,
}

impl AccountSecrets {
    pub fn new(school_id: i32, username: String, password: String) -> AccountSecrets {
        Self {
            school_id,
            username,
            password,
            untis_secrets: None,
        }
    }

    pub async fn from_encrypted(
        data: &[u8],
        key: &[u8; 32],
    ) -> Result<AccountSecrets, CryptorError> {
        decrypt_any(data, key).await
    }

    pub async fn encrypt(&self, key: &[u8; 32]) -> Result<Vec<u8>, CryptorError> {
        encrypt_any(&self, key).await
    }
}

/// Contains the account secrets for Untis <br>
/// This will be used for re-login. <br>
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Serialize, Deserialize)]
pub struct UntisSecrets {
    /// The internal school name from Untis and not the display name
    pub school_name: String,
    pub username: String,
    pub password: String,
}

impl UntisSecrets {
    pub fn new(school_name: String, username: String, password: String) -> UntisSecrets {
        Self {
            school_name,
            username,
            password,
        }
    }
}