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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
use chrono::{DateTime, NaiveDate, Utc};
use markup5ever::tendril::fmt::Slice;
use regex::Regex;
use reqwest::Client;
use serde::{Deserialize, Serialize};

use crate::utils::datetime::datetime_string_stupid_to_datetime;
use crate::{utils::constants::URL, Error};

#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
pub struct CalendarEntry {
    pub id: String,
    pub school_id: Option<i32>,
    pub external_uid: Option<String>,
    /// The person / group who is responsible for the entry / event
    pub responsible: Option<CalendarEntryPerson>,
    pub target_audience: Vec<CalendarEntryPerson>,
    pub title: String,
    /// May be empty
    pub description: String,
    pub start: DateTime<Utc>,
    pub end: DateTime<Utc>,
    pub last_modified: Option<DateTime<Utc>>,
    pub place: Option<String>,
    /// The study group of the entry (Lerngruppe)
    pub study_group: Option<StudyGroup>,
    pub category: Option<CalendarEntryCategory>,
    /// Indicates if an entry is new
    pub new: bool,
    /// Indicates if an entry is public
    pub public: bool,
    // Indicates if an entry is private
    pub private: bool,
    /// Indicates if an entry is secret (probably)
    pub secret: bool,
    pub all_day: bool,
}

/// May also be a group and not a single person
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
pub struct CalendarEntryPerson {
    pub id: String,
    pub name: String,
}

impl CalendarEntry {
    pub fn new(
        id: String,
        school_id: Option<i32>,
        external_uid: Option<String>,
        responsible: Option<CalendarEntryPerson>,
        target_audience: Vec<CalendarEntryPerson>,
        title: String,
        description: String,
        start: DateTime<Utc>,
        end: DateTime<Utc>,
        last_modified: Option<DateTime<Utc>>,
        place: Option<String>,
        study_group: Option<StudyGroup>,
        category: Option<CalendarEntryCategory>,
        new: bool,
        public: bool,
        private: bool,
        secret: bool,
        all_day: bool,
    ) -> Self {
        Self {
            id,
            school_id,
            external_uid,
            responsible,
            target_audience,
            title,
            description,
            start,
            end,
            last_modified,
            place,
            study_group,
            category,
            new,
            public,
            private,
            secret,
            all_day,
        }
    }
}

#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Serialize, Deserialize)]
pub struct StudyGroup {
    pub id: i32,
    pub name: String,
}

impl StudyGroup {
    pub fn new(id: i32, name: String) -> Self {
        Self { id, name }
    }
}

#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Serialize, Deserialize)]
pub struct CalendarEntryCategory {
    pub id: i32,
    pub name: String,
    /// a hexadecimal color (css)
    pub color: String,
}

/// Get all calendar entries in an specific time frame <br>
/// You can also use a optional search query to filter for events (this is server side)
pub async fn get_entries(
    from: NaiveDate,
    to: NaiveDate,
    search_query: Option<String>,
    client: &Client,
) -> Result<Vec<CalendarEntry>, Error> {
    let categories = match client.get(URL::CALENDAR).send().await {
        Ok(response) => {
            let html = match response.text().await {
                Ok(text) => text,
                Err(e) => {
                    return Err(Error::Html(format!(
                        "failed to parse html of '{}' with error '{}'",
                        URL::CALENDAR,
                        e
                    )))
                }
            };

            let json_categories = match html.split("var categories = new Array();").nth(1) {
                Some(part) => match part.split("var groups = new Array();").next() {
                    Some(part) => {
                        let content = part
                            .trim()
                            .replace("categories.push(", "")
                            .replace(");", ",")
                            .replace("id", "\"id\"")
                            .replace("name", "\"name\"")
                            .replace("color", "\"color\"")
                            .replace("logo", "\"logo\"")
                            .replace("\'", "\"");
                        let final_content = match content.rsplit_once(",") {
                            Some(split) => split.0.trim().to_string(),
                            None => content, // Happens if no categories exist at all
                        };

                        format!("[{}]", final_content.trim())
                    }
                    None => return Err(Error::Parsing(String::from(
                        "failed to parse json categories (missing first part of 'var groups...')",
                    ))),
                },
                None => return Err(Error::Parsing(String::from(
                    "failed to parse json categories (missing second part of 'var categories...')",
                ))),
            };

            let categories: Vec<CalendarEntryCategory> =
                match serde_json::from_str(json_categories.as_str()) {
                    Ok(result) => result,
                    Err(e) => {
                        return Err(Error::Parsing(format!(
                            "failed to parse json of categories with error '{}'",
                            e
                        )));
                    }
                };

            categories
        }
        Err(e) => {
            return Err(Error::Network(format!(
                "failed to get '{}' with error '{}'",
                URL::CALENDAR,
                e
            )))
        }
    };

    let f = String::from("getEvents");
    let s = search_query.unwrap_or_default();
    let start = format!("{}", from);
    let end = format!("{}", to);

    let events_json = match client
        .post(URL::CALENDAR)
        .form(&[("f", f), ("s", s), ("start", start), ("end", end)])
        .send()
        .await
    {
        Ok(response) => {
            // technically its a json but who cares
            match response.text().await {
                Ok(text) => text,
                Err(e) => {
                    return Err(Error::Html(format!(
                        "failed to parse html of '{}' with error '{}'",
                        URL::CALENDAR,
                        e
                    )))
                }
            }
        }
        Err(e) => {
            return Err(Error::Network(format!(
                "failed to post '{}' with error '{}'",
                URL::CALENDAR,
                e
            )))
        }
    };

    #[derive(Debug, Serialize, Deserialize)]
    struct JsonEvent {
        #[serde(rename = "Id")]
        id: String,
        #[serde(rename = "Institution")]
        school_id: Option<String>,
        #[serde(rename = "FremdUID")]
        external_uid: Option<String>,
        #[serde(rename = "Verantwortlich")]
        responsible_id: Option<String>,
        title: String,
        description: String,
        #[serde(rename = "Anfang")]
        start: String,
        #[serde(rename = "Ende")]
        end: String,
        #[serde(rename = "LetzteAenderung")]
        last_modified: Option<String>,
        #[serde(rename = "Ort")]
        place: Option<String>,
        #[serde(rename = "Lerngruppe")]
        study_group: Option<serde_json::Value>,
        category: Option<String>,
        #[serde(rename = "Neu")]
        new: String,
        #[serde(rename = "Oeffentlich")]
        public: String,
        #[serde(rename = "Privat")]
        private: String,
        #[serde(rename = "Geheim")]
        secret: String,
        #[serde(rename = "allDay")]
        all_day: bool,
    }

    let json_events: Vec<JsonEvent> = match serde_json::from_str(&events_json) {
        Ok(events) => events,
        Err(e) => {
            return Err(Error::Parsing(format!(
                "failed to parse json of events with error '{}'",
                e
            )));
        }
    };

    let mut entries = Vec::new();
    for json_event in json_events {
        let school_id: Option<i32> = match json_event.school_id {
            Some(id_string) => match id_string.parse() {
                Ok(school_id) => Some(school_id),
                Err(e) => {
                    return Err(Error::Parsing(format!(
                        "failed to parse school_id as i32 with error '{}'",
                        e
                    )));
                }
            },
            None => None,
        };

        let start = datetime_string_stupid_to_datetime(&json_event.start)
            .map_err(|e| {
                Error::DateTime(format!(
                    "failed to parse start datetime of entry with error '{}'",
                    e
                ))
            })?
            .to_utc();

        let end = datetime_string_stupid_to_datetime(&json_event.end)
            .map_err(|e| {
                Error::DateTime(format!(
                    "failed to parse end datetime of entry with error '{}'",
                    e
                ))
            })?
            .to_utc();

        let last_modified = match json_event.last_modified {
            Some(datetime_string) => Some(
                datetime_string_stupid_to_datetime(&datetime_string)
                    .map_err(|e| {
                        Error::DateTime(format!(
                            "failed to parse end datetime of entry with error '{}'",
                            e
                        ))
                    })?
                    .to_utc(),
            ),
            None => None,
        };

        let study_group = match json_event.study_group {
            Some(study_group) => match study_group.as_str() {
                Some(json_object) => {
                    #[derive(Deserialize)]
                    struct JsonStudyGroup {
                        #[serde(rename = "Name")]
                        name: String,
                        #[serde(rename = "Id")]
                        id: String,
                    }

                    let json_study_group: JsonStudyGroup = serde_json::from_str(&json_object)
                        .map_err(|e| {
                            Error::Parsing(format!(
                                "failed to parse json of study group with error '{}'",
                                e
                            ))
                        })?;

                    let id: i32 = json_study_group.id.parse().map_err(|e| {
                        Error::Parsing(format!(
                            "failed to parse study group id ({}) as i32 with error '{}'",
                            json_study_group.id, e
                        ))
                    })?;

                    Some(StudyGroup::new(id, json_study_group.name))
                }
                None => None,
            },
            None => None,
        };

        let category = match json_event.category {
            Some(json_object) => {
                let id: i32 = json_object.parse().map_err(|e| {
                    Error::Parsing(format!("failed to parse category id with error '{}'", e))
                })?;
                categories.iter().find(|&c| c.id == id).cloned()
            }
            None => None,
        };

        let new = json_event.new != "nein";
        let public = json_event.public != "nein";
        let private = json_event.private != "nein";
        let secret = json_event.secret != "nein";

        let (responsible_name, target_audience) = {
            #[derive(Deserialize)]
            struct JsonDetails {
                properties: JsonDetailsProperties,
            }

            #[derive(Deserialize)]
            struct JsonDetailsProperties {
                #[serde(rename = "zielgruppen")]
                target_audience: Option<serde_json::Value>,
                #[serde(rename = "verantwortlich")]
                responsible_name: Option<String>,
            }

            let json_details = match client
                .post(URL::CALENDAR)
                .form(&[("f", "getEvent"), ("id", json_event.id.as_str())])
                .send()
                .await
            {
                Ok(response) => response.text().await.map_err(|e| {
                    Error::Html(format!(
                        "failed to parse html / json of entry details as text with error '{}'",
                        e
                    ))
                })?,
                Err(e) => {
                    return Err(Error::Network(format!(
                        "failed to post '{}' with error '{}'",
                        URL::CALENDAR,
                        e
                    )))
                }
            };

            let details: JsonDetails = serde_json::from_str(&json_details).map_err(|e| {
                Error::Parsing(format!(
                    "failed to parse json of entry details ({}) with error '{}'",
                    json_event.id, e
                ))
            })?;

            let raw_target_audience = details.properties.target_audience.unwrap_or_default();
            let json_target_audience = raw_target_audience.to_string();
            let target_audience_split = json_target_audience.split(",");

            let mut targets = Vec::new();
            for target in target_audience_split {
                let (broken_id, name) = target.split_once(":").unwrap_or_default();

                let id = broken_id
                    .replace("\"", "")
                    .replacen("-", "", 1)
                    .replacen("{", "", 1)
                    .trim()
                    .to_string();
                let name = name.replace("\"", "").replace("}", "").trim().to_string();

                if broken_id.is_empty() || name.is_empty() {
                    continue;
                }

                targets.push(CalendarEntryPerson { id, name });
            }

            (
                details
                    .properties
                    .responsible_name
                    .unwrap_or_default()
                    .trim()
                    .to_string(),
                targets,
            )
        };

        let responsible = match json_event.responsible_id {
            Some(id) => {
                if id.is_empty() || responsible_name.is_empty() {
                    None
                } else {
                    Some(CalendarEntryPerson {
                        id,
                        name: responsible_name,
                    })
                }
            }
            None => None,
        };

        entries.push(CalendarEntry::new(
            json_event.id,
            school_id,
            json_event.external_uid,
            responsible,
            target_audience,
            json_event.title,
            json_event.description,
            start,
            end,
            last_modified,
            json_event.place,
            study_group,
            category,
            new,
            public,
            private,
            secret,
            json_event.all_day,
        ));
    }

    Ok(entries)
}

#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
pub struct CalendarExports {
    /// All available years (PDF and CSV) <br>
    /// These years refer to School years so 2024 is 2024/2025
    pub available_years: Vec<i32>,
}

#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
pub enum CalendarExportFileType {
    PDF(CalendarExportFileTypePDF),
    /// The i32 represents the year <br>
    /// NOTE: Make sure the year is available
    CSV(i32),
    /// The i32 represents the year <br>
    /// NOTE: Make sure the year is available
    ICS(i32),
}

#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
pub enum CalendarExportFileTypePDF {
    CurrentDay,
    NextDay,
    CurrentWeek,
    NextWeek,
    /// The i32 represents the year <br>
    /// NOTE: Make sure the year is available
    YearSimple(i32),
    /// The i32 represents the year <br>
    /// NOTE: Make sure the year is available
    YearDetailed(i32),
    /// The i32 represents the year <br>
    /// NOTE: Make sure the year is available
    YearMonthView(i32),
}

impl CalendarExports {
    pub fn new(available_years: Vec<i32>) -> Self {
        Self { available_years }
    }

    pub async fn get(client: &Client) -> Result<Self, Error> {
        let response = client.get(URL::CALENDAR).send().await.map_err(|e| {
            Error::Network(format!("failed to get {} with error {}", URL::CALENDAR, e))
        })?;

        let html = response.text().await.map_err(|e| {
            Error::Html(format!(
                "failed to parse HTML of response from '{}' with error '{}'",
                URL::CALENDAR,
                e
            ))
        })?;

        let regex = Regex::new(r"year=(\d\d\d\d)")
            .map_err(|e| Error::Parsing(format!("failed to create regex with error '{}'", e)))?;
        let captures: Vec<_> = regex.captures_iter(&html).collect();

        let mut years: Vec<i32> = Vec::new();
        for capture_group in captures {
            if let Some(year) = capture_group.get(1) {
                if let Ok(year) = year.as_str().parse() {
                    years.push(year);
                }
            }
        }

        Ok(Self::new(years))
    }

    /// Get the iCal url (automatic updates)
    pub async fn get_ical(client: &Client) -> Result<String, Error> {
        client
            .post(URL::CALENDAR)
            .form(&[("f", "iCalAbo")])
            .send()
            .await
            .map_err(|e| {
                Error::Network(format!(
                    "failed to post '{}' with error '{}'",
                    URL::CALENDAR,
                    e
                ))
            })?
            .text()
            .await
            .map_err(|e| {
                Error::Parsing(format!(
                    "failed to parse text of response with error '{}'",
                    e
                ))
            })
    }

    /// Export a file with the specific type
    pub async fn get_export(
        &self,
        client: &Client,
        export_type: CalendarExportFileType,
        path: &str,
    ) -> Result<(), Error> {
        let url = match export_type {
            CalendarExportFileType::PDF(pdf_type) => match pdf_type {
                CalendarExportFileTypePDF::CurrentDay => {
                    "https://start.schulportal.hessen.de/kalender.php?a=export&export=pdf&day=1"
                        .to_string()
                }
                CalendarExportFileTypePDF::NextDay => {
                    "https://start.schulportal.hessen.de/kalender.php?a=export&export=pdf&day=2"
                        .to_string()
                }
                CalendarExportFileTypePDF::CurrentWeek => {
                    "https://start.schulportal.hessen.de/kalender.php?a=export&export=pdf&week=1"
                        .to_string()
                }
                CalendarExportFileTypePDF::NextWeek => {
                    "https://start.schulportal.hessen.de/kalender.php?a=export&export=pdf&week=2"
                        .to_string()
                }
                CalendarExportFileTypePDF::YearSimple(year) => {
                    match self.available_years.contains(&year) {
                        true => format!("https://start.schulportal.hessen.de/kalender.php?a=export&export=pdf&year={}", year),
                        false => return Err(Error::InvalidInput(format!("year '{}' is not available!", year)))
                    }
                }
                CalendarExportFileTypePDF::YearDetailed(year) => {
                    match self.available_years.contains(&year) {
                        true => format!("https://start.schulportal.hessen.de/kalender.php?a=export&export=pdf-extended&year={}", year),
                        false => return Err(Error::InvalidInput(format!("year '{}' is not available!", year)))
                    }
                }
                CalendarExportFileTypePDF::YearMonthView(year) => {
                    match self.available_years.contains(&year) {
                        true => format!("https://start.schulportal.hessen.de/kalender.php?a=export&export=wandkalender&year={}", year),
                        false => return Err(Error::InvalidInput(format!("year '{}' is not available!", year)))
                    }
                }
            },
            CalendarExportFileType::CSV(year) => match self.available_years.contains(&year) {
                true => format!(
                    "https://start.schulportal.hessen.de/kalender.php?a=export&export=csv&year={}",
                    year
                ),
                false => {
                    return Err(Error::InvalidInput(format!(
                        "year '{}' is not available!",
                        year
                    )))
                }
            },
            CalendarExportFileType::ICS(year) => match self.available_years.contains(&year) {
                true => format!(
                    "https://start.schulportal.hessen.de/kalender.php?a=export&export=ical&year={}",
                    year
                ),
                false => {
                    return Err(Error::InvalidInput(format!(
                        "year '{}' is not available!",
                        year
                    )))
                }
            },
        };

        let response =
            client.get(&url).send().await.map_err(|e| {
                Error::Network(format!("failed to get '{}' with error '{}'", url, e))
            })?;

        let bytes = response.bytes().await.map_err(|e| {
            Error::Parsing(format!(
                "failed to parse response as bytes with error '{}'",
                e
            ))
        })?;

        let mut file = tokio::fs::File::create(path).await.map_err(|e| {
            Error::FileSystem(format!(
                "failed to create file at '{}' with error '{}'",
                path, e
            ))
        })?;

        tokio::io::copy(&mut bytes.as_bytes(), &mut file)
            .await
            .map_err(|e| Error::FileSystem(format!("failed to save file with error '{}'", e)))?;

        Ok(())
    }
}