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
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
use crate::base::account::Account;
use crate::utils::constants::URL;
use crate::utils::conversion::string_to_byte_size;
use crate::utils::crypt::{decrypt_lanis_encoded_tags, encrypt_lanis_data};
use crate::utils::datetime::date_time_string_to_datetime;
use crate::{Error, LessonUploadError};
use chrono::{DateTime, Datelike, Utc};
use markup5ever::interface::tree_builder::TreeSink;
use regex::Regex;
use reqwest::header::HeaderMap;
use reqwest::multipart::Part;
use reqwest::Client;
use scraper::{Element, ElementRef, Html, Selector};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::path::Path;
use std::time::SystemTime;
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
pub struct Lesson {
pub id: i32,
pub url: String,
pub name: String,
pub teacher: String,
/// Should always be Some if nothing went wrong
pub teacher_short: Option<String>,
pub attendances: BTreeMap<String, String>,
/// If this is None there is no latest entry
pub entry_latest: Option<LessonEntry>,
/// Will be empty if no entries are found and None if this value wasn't initialized
pub entries: Option<Vec<LessonEntry>>,
/// Will be empty if no marks are found and None if this value wasn't initialized
pub marks: Option<Vec<LessonMark>>,
/// Will be empty if no exams are found and None if this value wasn't initialized
pub exams: Option<Vec<LessonExam>>,
}
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
pub struct LessonEntry {
pub id: i32,
pub date: DateTime<Utc>,
pub school_hours: Vec<i32>,
pub title: String,
pub details: Option<String>,
pub homework: Option<Homework>,
pub attachments: Option<Vec<Attachment>>,
pub attachment_number: i32,
pub uploads: Option<Vec<LessonUpload>>,
}
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Serialize, Deserialize)]
pub struct Attachment {
pub name: String,
pub size: u64,
pub url: String,
}
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Serialize, Deserialize)]
pub struct Homework {
pub description: String,
pub completed: bool,
}
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
pub struct LessonUpload {
pub id: i32,
pub name: String,
/// True if open and false if closed
pub state: bool,
pub url: String,
pub uploaded: Option<String>,
pub date: Option<DateTime<Utc>>,
pub info: Option<LessonUploadInfo>,
}
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
pub struct LessonUploadInfo {
pub course_id: Option<i32>,
pub entry_id: Option<i32>,
pub start: Option<DateTime<Utc>>,
pub end: Option<DateTime<Utc>>,
/// Represents if multiple files can be uploaded
pub multiple_files: bool,
/// Represents if files can be uploaded unlimited times
pub unlimited_tries: bool,
pub visibility: Option<String>,
pub automatic_deletion: Option<String>,
pub allowed_file_types: Vec<String>,
pub max_file_size: String,
/// Has some extra info
pub extra: Option<String>,
pub own_files: Vec<LessonUploadInfoOwnFile>,
pub public_files: Vec<LessonUploadInfoPublicFile>,
}
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Serialize, Deserialize)]
pub struct LessonUploadInfoOwnFile {
pub name: String,
pub url: String,
pub index: i32,
pub comment: Option<String>,
}
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Serialize, Deserialize)]
pub struct LessonUploadInfoPublicFile {
pub name: String,
pub url: String,
pub index: i32,
pub person: String,
}
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Serialize, Deserialize)]
pub struct LessonUploadFileStatus {
pub name: String,
pub status: String,
pub message: Option<String>,
}
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
pub struct LessonMark {
pub name: String,
pub date: DateTime<Utc>,
pub mark: String,
pub comment: Option<String>,
}
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Serialize, Deserialize)]
pub struct LessonExam {
pub date: String,
pub name: String,
pub finished: bool,
}
impl Lesson {
/**
* Sets the data for a lesson. This data includes: <br>
* Entries history, marks and class tests
*/
pub async fn set_data(&mut self, account: &Account) -> Result<(), Error> {
let client = &account.client;
match client
.get(format!("{}{}", URL::BASE, &self.url))
.send()
.await
{
Ok(response) => {
if !response.status().is_success() {
return Err(Error::Network(format!(
"Failed request with status code: {}",
response.status()
)));
}
let document = decrypt_lanis_encoded_tags(
response.text().await.unwrap().as_str(),
&account.key_pair.public_key_string,
)
.await;
let document = Html::parse_document(&document);
let mut history: Vec<LessonEntry> = vec![];
let history_doc_selector = Selector::parse("#history").unwrap();
let history_doc = document.select(&history_doc_selector);
let history_doc = history_doc.clone().next().unwrap().html();
let mut history_doc = Html::parse_document(&history_doc);
let history_table_rows_selector = Selector::parse("table>tbody>tr").unwrap();
let hidden_div_selector = Selector::parse(".hidden_encoded").unwrap();
let hidden_div_ids: Vec<_> = history_doc
.select(&hidden_div_selector)
.map(|x| x.id())
.collect();
// Remove encoded divs
for id in hidden_div_ids {
history_doc.remove_from_parent(&id);
}
let history_table_rows = history_doc.select(&history_table_rows_selector);
// Selectors for loop
let title_selector = Selector::parse("td>b").unwrap();
let details_selector = Selector::parse("span.markup i.fa-comment-alt").unwrap();
let homework_selector =
Selector::parse("span.homework + br + span.markup").unwrap();
let homework_done_selector = Selector::parse("span.done.hidden").unwrap();
let file_alert_selector = Selector::parse("div.alert.alert-info>a").unwrap();
let files_selector = Selector::parse(".files").unwrap();
let upload_group_selector = Selector::parse("div.btn-group").unwrap();
let open_upload_selector = Selector::parse(".btn-warning").unwrap();
let closed_upload_selector = Selector::parse(".btn-default").unwrap();
let upload_url_selector = Selector::parse("ul.dropdown-menu li a").unwrap();
let upload_badge_selector = Selector::parse("span.badge").unwrap();
let small_selector = Selector::parse("small").unwrap();
for row in history_table_rows {
let id = row.attr("data-entry").unwrap().parse::<i32>().unwrap();
let title = {
row.child_elements()
.nth(1)
.unwrap()
.select(&title_selector)
.next()
.unwrap()
.text()
.next()
.unwrap()
.trim()
.to_string()
};
let details = {
let details = row.select(&details_selector).next();
if details.is_some() {
let details = details.unwrap();
let details = details
.parent_element()
.unwrap()
.text()
.next()
.unwrap()
.trim()
.to_string();
Some(details)
} else {
None
}
};
let homework = {
let homework_element = row.select(&homework_selector).next();
let mut description: String = String::new();
if homework_element.is_some() {
for text in homework_element.unwrap().text() {
description += &*format!("{}\n", text.trim()).to_string();
}
description =
description.rsplit_once('\n').unwrap().0.trim().to_string();
}
let completed = {
let element = row.select(&homework_done_selector).next();
!element.is_some()
};
if description.is_empty() {
None
} else {
Some(Homework {
description,
completed,
})
}
};
let attachments: Option<Vec<Attachment>> = {
if row
.child_elements()
.nth(1)
.unwrap()
.select(&file_alert_selector)
.next()
.is_some()
{
let mut attachments = vec![];
let url = format!(
"{}{}",
URL::BASE,
row.child_elements()
.nth(1)
.unwrap()
.select(&file_alert_selector)
.next()
.unwrap()
.value()
.attr("href")
.unwrap()
);
let url = url.replace("&b=zip", "").to_string();
for element in
row.select(&files_selector).nth(0).unwrap().child_elements()
{
let name = element.attr("data-file").unwrap().to_string();
let size = match element.select(&small_selector).nth(0) {
Some(element) => string_to_byte_size(
element
.text()
.collect::<String>()
.replace("(", "")
.replace(")", "")
.trim()
.to_string(),
)
.await
.map_err(|e| {
Error::Parsing(format!(
"failed to parse file size: '{}'",
e
))
})?,
None => 0,
};
let url = format!("{}&f={}", url, name);
attachments.push(Attachment { name, size, url });
}
Some(attachments)
} else {
None
}
};
let uploads: Option<Vec<LessonUpload>> = {
let upload_groups = row
.child_elements()
.nth(1)
.unwrap()
.select(&upload_group_selector);
let mut uploads: Vec<LessonUpload> = vec![];
for group in upload_groups {
let open = group.select(&open_upload_selector).next();
let closed = group.select(&closed_upload_selector).next();
if open.is_some() {
let open = open.unwrap();
let name = open
.children()
.nth(2)
.unwrap()
.value()
.as_text()
.unwrap()
.replace("\n", "")
.trim()
.to_string();
let state = true;
let url = format!(
"{}{}",
URL::BASE,
group
.select(&upload_url_selector)
.next()
.unwrap()
.value()
.attr("href")
.unwrap()
);
let uploaded = {
match open.select(&upload_badge_selector).next() {
Some(element) => Some(
element.text().collect::<String>().trim().to_string(),
),
None => None,
}
};
let date = {
let text = open
.select(&small_selector)
.next()
.unwrap()
.text()
.collect::<String>()
.trim()
.to_string();
let text = text.replace("\n", "").trim().to_string();
let text = text.replace(" ", "").trim().to_string();
let text = text.replace("bis ", "").trim().to_string();
let text = text.replace("um", "").trim().to_string();
let text = text.replace(",", "").trim().to_string();
let text = text.replace(" den", "").trim().to_string();
let text = text.replace(" Uhr", "").trim().to_string();
let split = text.split(" ");
let date = format!(
"{}{}",
split.clone().nth(1).unwrap_or_default(),
chrono::Local::now().year(),
);
let time = format!("{}:00", split.last().unwrap_or_default());
println!("text is: {}", text);
date_time_string_to_datetime(date.as_str(), time.as_str())
.map_err(|e| {
Error::DateTime(format!(
"failed to convert date to DateTime '{:?}'",
e
))
})?
.to_utc()
};
let id = url.split("&id=").last().unwrap().parse::<i32>().unwrap();
uploads.push(LessonUpload {
id,
name,
state,
url,
uploaded: {
if uploaded.is_some() {
Some(uploaded.unwrap())
} else {
None
}
},
date: Some(date),
info: None,
});
} else if closed.is_some() {
let closed = closed.unwrap();
let name = closed
.children()
.nth(2)
.unwrap()
.value()
.as_text()
.unwrap()
.replace("\n", "")
.trim()
.to_string();
let state = false;
let url = format!(
"{}{}",
URL::BASE,
group
.select(&upload_url_selector)
.next()
.unwrap()
.value()
.attr("href")
.unwrap()
);
let uploaded = {
match closed.select(&upload_badge_selector).next() {
Some(element) => Some(
element.text().collect::<String>().trim().to_string(),
),
None => None,
}
};
let id = url.split("&id=").last().unwrap().parse::<i32>().unwrap();
uploads.push(LessonUpload {
id,
name,
state,
url,
uploaded: {
if uploaded.is_some() {
Some(uploaded.unwrap())
} else {
None
}
},
date: None,
info: None,
})
}
}
if uploads.is_empty() {
None
} else {
Some(uploads)
}
};
let date = row
.child_elements()
.nth(0)
.unwrap()
.text()
.collect::<String>()
.split("\n")
.nth(0)
.unwrap()
.trim()
.to_string();
let date = date_time_string_to_datetime(date.as_str(), "02:00:00")
.map_err(|e| {
Error::DateTime(format!("failed to convert date to DateTime '{:?}'", e))
})?
.to_utc();
let school_hours = {
let mut school_hours = vec![];
let string = row
.child_elements()
.nth(0)
.unwrap()
.text()
.collect::<String>()
.split("\n")
.nth(2)
.unwrap()
.trim()
.replace(". ", "")
.replace("Stunde", "")
.replace("-", "")
.trim()
.to_string();
for hour in string.split(' ') {
school_hours.push(hour.parse::<i32>().unwrap_or_default())
}
school_hours
};
history.push(LessonEntry {
id,
date,
school_hours,
title,
details,
homework: {
if homework.is_some() {
Some(homework.unwrap())
} else {
None
}
},
attachments: {
if attachments.is_some() {
Some(attachments.clone().unwrap())
} else {
None
}
},
attachment_number: {
if attachments.is_some() {
attachments.unwrap().len() as i32
} else {
0
}
},
uploads: {
if uploads.is_some() {
Some(uploads.unwrap())
} else {
None
}
},
})
}
self.entries = Some(history);
// Marks
let marks_section_selector = Selector::parse("#marks").unwrap();
let mut marks_doc = Html::parse_document(
&document
.select(&marks_section_selector)
.nth(0)
.unwrap()
.html(),
);
let encoded_elements: Vec<_> = marks_doc
.select(&hidden_div_selector)
.map(|x| x.id())
.collect();
for id in encoded_elements {
marks_doc.remove_from_parent(&id)
}
let marks_table_rows_selector = Selector::parse("table>tbody>tr").unwrap();
let td_selector = Selector::parse("td").unwrap();
let comment_info_selector = Selector::parse("span.fa.fa-comment").unwrap();
let marks_table_rows = marks_doc.select(&marks_table_rows_selector);
let mut marks = vec![];
for row in marks_table_rows {
if row.child_elements().count() == 3 {
let name = row
.child_elements()
.nth(0)
.unwrap()
.text()
.collect::<String>()
.trim()
.to_string();
let date = date_time_string_to_datetime(
&format!(
"{}{}",
row.child_elements()
.nth(1)
.unwrap()
.text()
.collect::<String>()
.trim()
.split_once(",")
.unwrap_or_default()
.1
.trim(),
chrono::Local::now().year()
),
"02:00:00",
)
.map_err(|e| {
Error::DateTime(format!("failed to convert date to DateTime '{:?}'", e))
})?
.to_utc();
let mark = row
.child_elements()
.nth(2)
.unwrap()
.text()
.collect::<String>()
.trim()
.to_string();
let comment = match row.next_sibling_element() {
Some(element) => match element.select(&td_selector).nth(1) {
Some(comment_element) => {
if let Some(_) =
comment_element.select(&comment_info_selector).nth(0)
{
Some(
comment_element
.text()
.collect::<String>()
.trim()
.to_string()
.split(':')
.nth(1)
.unwrap_or_default()
.trim()
.to_string(),
)
} else {
None
}
}
None => None,
},
None => None,
};
marks.push(LessonMark {
name,
date,
mark,
comment,
});
}
}
self.marks = Some(marks);
// Exams
let exam_section_selector = Selector::parse("#klausuren").unwrap();
let exam_section = document.select(&exam_section_selector).nth(0).unwrap();
let ul_selector = Selector::parse("ul").unwrap();
let li_selector = Selector::parse("li").unwrap();
let title_selector = Selector::parse("h2").unwrap();
let mut exams = vec![];
if !exam_section
.child_elements()
.nth(0)
.unwrap()
.html()
.contains("Diese Kursmappe beinhaltet leider noch keine Leistungskontrollen!")
{
for element in exam_section.child_elements() {
let elements = element.select(&ul_selector);
for element in elements {
let sibling_html = Html::parse_document(
&element.prev_sibling_element().unwrap().html(),
);
let title = sibling_html
.select(&title_selector)
.nth(0)
.unwrap()
.text()
.collect::<String>()
.trim()
.to_string();
let re = Regex::new(r"\s+\n").unwrap();
let li_elements = element.select(&li_selector);
for element in li_elements {
let exam = {
let text =
element.text().collect::<String>().trim().to_string();
let mut result =
re.replace_all(text.as_str(), "").trim().to_string();
let mut trimming = true;
while trimming {
let previous = result.clone();
result = result.replace(" ", " ").trim().to_string();
if result == previous {
trimming = false;
}
}
result = result.replace("\n", "").trim().to_string();
result
};
let split = exam.split(" ");
let date = split.clone().nth(0).unwrap().trim().to_string();
let name = {
let mut result = "".to_string();
for i in 1..split.clone().count() {
result =
format!("{} {}", result, split.clone().nth(i).unwrap());
}
result.trim().to_string()
};
exams.push(LessonExam {
date,
name,
finished: {
if title == "Alle Leistungskontrolle(n)" {
true
} else {
false
}
},
});
}
}
}
}
self.exams = Some(exams);
Ok(())
}
Err(error) => Err(Error::Network(format!(
"Failed to get '{}{}' with error: {}",
URL::BASE,
&self.url,
error
))),
}
}
}
impl Homework {
pub async fn set_homework(
&mut self,
state: bool,
course_id: i32,
entry_id: i32,
client: &Client,
) -> Result<(), Error> {
match client
.post(URL::MEIN_UNTERRICHT)
.header("X-Requested-With", "XMLHttpRequest")
.form(&[
("a", "sus_homeworkDone"),
("entry", entry_id.to_string().as_str()),
("id", course_id.to_string().as_str()),
("b", {
if state {
"done"
} else {
"undone"
}
}),
])
.send()
.await
{
Ok(response) => {
let text = response.text().await.unwrap();
if text == "1" {
self.completed = state;
Ok(())
} else {
Err(Error::ServerSide(format!(
"Failed to set homework! Got instead of '1' '{}' as response",
text
)))
}
}
Err(e) => Err(Error::Network(format!(
"Failed to set homework with error: {}",
e
))),
}
}
}
impl LessonUpload {
pub async fn get_info(&self, client: &Client) -> Result<LessonUploadInfo, Error> {
match client.get(&self.url).send().await {
Ok(response) => {
let document = Html::parse_document(&response.text().await.unwrap());
let requirements_selector =
Selector::parse("div#content div.row div.col-md-12").unwrap();
let requirements = document.select(&requirements_selector).nth(1).unwrap();
async fn select_option_string(
selector: &Selector,
element: &ElementRef<'_>,
) -> Option<String> {
match element.select(&selector).nth(0) {
Some(element) => {
let result = element.text().collect::<String>().trim().to_string();
Some(result)
}
None => None,
}
}
let start_selector = Selector::parse("span.editable").unwrap();
let start = select_option_string(&start_selector, &requirements);
let end_selector = Selector::parse("b span.editable").unwrap();
let end = select_option_string(&end_selector, &requirements);
let bool_selector =
Selector::parse("i.fa.fa-check-square-o.fa-fw + span.label.label-success")
.unwrap();
let mut bool_select = requirements.select(&bool_selector);
let multiple_files = {
if bool_select
.clone()
.nth(0)
.unwrap()
.text()
.collect::<String>()
.trim()
== "erlaubt"
{
true
} else {
false
}
};
let unlimited_tries = {
match bool_select.nth(1) {
Some(option) => {
if option.text().collect::<String>().trim() == "erlaubt" {
true
} else {
false
}
}
None => false,
}
};
let visibility_selector_0 =
Selector::parse("i.fa.fa-eye.fa-fw + span.label").unwrap();
let visibility_selector_1 =
Selector::parse("i.fa.fa-eye-slash.fa-fw + span.label").unwrap();
let visibility = requirements
.select(&visibility_selector_0)
.nth(0)
.and_then(|e| Some(e.text().collect::<String>().trim().to_string()))
.or_else(|| {
requirements
.select(&visibility_selector_1)
.nth(0)
.and_then(|e| Some(e.text().collect::<String>().trim().to_string()))
.or_else(|| None)
});
let automatic_deletion_selector =
Selector::parse("i.fa.fa-trash-o.fa-fw + span.label.label-info").unwrap();
let automatic_deletion =
select_option_string(&automatic_deletion_selector, &requirements);
let string_select_selector =
Selector::parse("i.fa.fa-file.fa-fw + span.label.label-warning").unwrap();
let mut string_select = requirements.select(&string_select_selector);
let allowed_file_types = {
let mut result = vec![];
let s = string_select
.nth(0)
.unwrap()
.text()
.collect::<String>()
.trim()
.to_string();
let split = s.split(", ");
for s in split {
result.push(s.to_string());
}
result
};
let max_file_size = string_select
.nth(0)
.unwrap()
.text()
.collect::<String>()
.trim()
.to_string();
let extra_selector = Selector::parse("div.alert.alert-info").unwrap();
let extra = {
match select_option_string(&extra_selector, &requirements).await {
Some(s) => Some(s.split("\n").nth(1).unwrap().trim().to_string()),
None => None,
}
};
let own_files_element_selector =
Selector::parse("div#content div.row div.col-md-12").unwrap();
let own_files_element =
document.select(&own_files_element_selector).nth(2).unwrap();
let ul_ui_selector = Selector::parse("ul li").unwrap();
let own_files_element_for = own_files_element.select(&ul_ui_selector);
let mut own_files = vec![];
let file_index_re = Regex::new(r"f=(\d+)").unwrap();
let a_selector = Selector::parse("a").unwrap();
for element in own_files_element_for {
let a = element.select(&a_selector).nth(0).unwrap();
let href = a.value().attr("href").unwrap();
let name = a.text().collect::<String>().trim().to_string();
let url = format!("{}{}", URL::BASE, href);
let index = file_index_re
.captures(&href)
.unwrap()
.get(1)
.unwrap()
.as_str()
.to_string()
.parse::<i32>()
.map_err(|_| {
Error::Parsing("Failed to parse index of file as i32".to_string())
})?;
let comment = {
match element.children().nth(9) {
Some(node) => {
// TODO: TEST
match node.value().as_text() {
Some(text) => Some(text.trim().to_string()),
None => None,
}
}
None => None,
}
};
own_files.push(LessonUploadInfoOwnFile {
name,
url,
index,
comment,
})
}
let upload_form_selector = Selector::parse("div.col-md-7 form").unwrap();
let course_id_selector = Selector::parse("input[name='b']").unwrap();
let mut course_id = None;
let entry_id_selector = Selector::parse("input[name='e']").unwrap();
let mut entry_id = None;
match document.select(&upload_form_selector).nth(0) {
Some(form) => {
course_id = Some(
form.select(&course_id_selector)
.nth(0)
.unwrap()
.attr("value")
.unwrap()
.parse::<i32>()
.unwrap(),
);
entry_id = Some(
form.select(&entry_id_selector)
.nth(0)
.unwrap()
.attr("value")
.unwrap()
.parse::<i32>()
.unwrap(),
);
}
None => (),
}
let mut public_files = vec![];
let public_files_selector =
Selector::parse("div#content div.row div.col-md-5").unwrap();
let person_selector = Selector::parse("span.label.label-info").unwrap();
match document.select(&public_files_selector).nth(0) {
Some(public_files_element) => {
for element in public_files_element.select(&ul_ui_selector) {
let a = element.select(&a_selector).nth(0).unwrap();
let href = a.value().attr("href").unwrap();
let name = a.text().collect::<String>().trim().to_string();
let url = format!("{}{}", URL::BASE, href);
let person = element
.select(&person_selector)
.nth(0)
.unwrap()
.text()
.collect::<String>()
.trim()
.to_string();
let index = file_index_re
.captures(&href)
.unwrap()
.get(1)
.unwrap()
.as_str()
.to_string()
.parse::<i32>()
.map_err(|_| {
Error::Parsing(
"Failed to parse index of file as i32".to_string(),
)
})?;
public_files.push(LessonUploadInfoPublicFile {
name,
url,
person,
index,
})
}
}
None => (),
}
let start = start.await;
let end = end.await;
let automatic_deletion = automatic_deletion.await;
async fn parse_date_time(s: String) -> Result<DateTime<Utc>, Error> {
let ymd = format!("{}", &s.split(" ").nth(2).unwrap());
let hms = format!("{}:{}", s.split(" ").nth(3).unwrap(), "00");
let result = date_time_string_to_datetime(&ymd, &hms);
Ok(result
.map_err(|_| {
Error::DateTime("failed to convert lanis time to cron time".to_string())
})?
.to_utc())
}
let start = {
match start {
Some(start) => {
let s = start.replace(", ab", "");
Some(parse_date_time(s).await?)
}
None => None,
}
};
let end = {
match end {
Some(end) => {
let s = end.replace(", spätestens", "");
Some(parse_date_time(s).await?)
}
None => None,
}
};
let result = LessonUploadInfo {
course_id,
entry_id,
start,
end,
multiple_files,
unlimited_tries,
visibility,
automatic_deletion,
allowed_file_types,
max_file_size,
extra,
own_files,
public_files,
};
Ok(result)
}
Err(e) => Err(Error::Network(format!(
"Failed to fetch upload info with error: '{}'",
e
))),
}
}
/// Takes a vector of file paths (max. 5) and uploads these files to Lanis. <br>
/// [LessonUpload::get_info] must be called before calling this function
pub async fn upload(
&self,
files: Vec<&Path>,
client: &Client,
) -> Result<Vec<LessonUploadFileStatus>, Error> {
if self.info.is_none() {
return Err(Error::Parsing("No info found in lessons!".to_string()));
}
if files.is_empty() {
return Err(Error::Parsing("No files found in lessons!".to_string()));
}
let upload_info = self.info.clone().unwrap();
let course_id = upload_info.course_id.unwrap();
let entry_id = upload_info.entry_id.unwrap();
let form = reqwest::multipart::Form::new()
.part("a", Part::text("sus_abgabe"))
.part("b", Part::text(course_id.to_string()))
.part("e", Part::text(entry_id.to_string()))
.part("id", Part::text(self.id.to_string()))
.part("file1", {
match files.get(0) {
Some(path) => Part::file(path).await.unwrap(),
None => Part::bytes(&[]),
}
})
.part("file2", {
match files.get(1) {
Some(path) => Part::file(path).await.unwrap(),
None => Part::bytes(&[]),
}
})
.part("file3", {
match files.get(2) {
Some(path) => Part::file(path).await.unwrap(),
None => Part::bytes(&[]),
}
})
.part("file4", {
match files.get(3) {
Some(path) => Part::file(path).await.unwrap(),
None => Part::bytes(&[]),
}
})
.part("file5", {
match files.get(4) {
Some(path) => Part::file(path).await.unwrap(),
None => Part::bytes(&[]),
}
});
let mut headers = HeaderMap::new();
headers.insert("Accept", "*/*".parse().unwrap());
headers.insert("Accept-Encoding", "text".parse().unwrap());
headers.insert("Sec-Fetch-Dest", "document".parse().unwrap());
headers.insert("Sec-Fetch-Mode", "navigate".parse().unwrap());
headers.insert("Sec-Fetch-Site", "same-origin".parse().unwrap());
//return Ok(vec![LessonUploadFileStatus{
// name: "Not yet finished".to_string(),
// status: "Same".to_string(),
// message: Some("Same again".to_string()),
//}]);
match client
.post(URL::MEIN_UNTERRICHT)
.headers(headers)
.multipart(form)
.send()
.await
{
Ok(response) => {
let text = response.text().await.unwrap();
let document = Html::parse_document(&text);
let status_message_group_selector =
Selector::parse("div#content div.col-md-12").unwrap();
let status_message_group = document
.select(&status_message_group_selector)
.nth(2)
.unwrap();
let ul_ui_selector = Selector::parse("ul li").unwrap();
let b_selector = Selector::parse("b").unwrap();
let span_label_selector = Selector::parse("span.label").unwrap();
let mut status_messages = vec![];
for status_message in status_message_group.select(&ul_ui_selector) {
let name = status_message.select(&b_selector).nth(0);
if name.is_none() {
return Err(Error::ServerSide("Failed to upload any file!".to_string()));
}
let status = status_message
.select(&span_label_selector)
.nth(0)
.unwrap()
.text()
.collect::<String>()
.trim()
.to_string();
let message = {
match status_message.children().nth(4) {
Some(message) => match message.value().as_text() {
Some(text) => {
let result = text.trim().to_string();
Some(result)
}
None => None,
},
None => None,
}
};
let name = {
if message.is_some() {
let message = message.clone().unwrap();
if !message.contains(
"Datei mit gleichem Namen schon vorhanden. Datei umbenannt in ",
) {
name.unwrap().text().collect::<String>().trim().to_string()
} else {
message
.split("\"")
.nth(1)
.unwrap()
.replace("\"", "")
.to_string()
}
} else {
name.unwrap().text().collect::<String>().trim().to_string()
}
};
status_messages.push(LessonUploadFileStatus {
name,
status,
message,
})
}
Ok(status_messages)
}
Err(e) => Err(Error::Network(format!(
"Failed to upload file with error: '{}'",
e.to_string()
))),
}
}
/// Deletes an already uploaded File (Takes a file id)
pub async fn delete(&self, file: &i32, account: &Account) -> Result<(), Error> {
let client = &account.client;
let encrypted_password = encrypt_lanis_data(
account.secrets.password.as_bytes(),
&account.key_pair.public_key_string,
);
if self.info.is_none() {
return Err(Error::LessonUploadError(LessonUploadError::NoInfo));
}
let info = self.info.clone().unwrap();
if info.course_id.is_none() || info.entry_id.is_none() {
return Err(Error::LessonUploadError(LessonUploadError::NoInfo));
}
let course_id = info.course_id.clone().unwrap();
let entry_id = info.entry_id.clone().unwrap();
let encrypted_password = encrypted_password.await;
match client
.post(URL::MEIN_UNTERRICHT)
.form(&[
("a", "sus_abgabe"),
("d", "delete"),
("b", &course_id.to_string()),
("e", &entry_id.to_string()),
("id", &self.id.to_string()),
("f", &file.to_string()),
("pw", &encrypted_password),
])
.send()
.await
{
Ok(response) => match response.text().await.unwrap().parse::<i32>().unwrap() {
-2 => Err(Error::LessonUploadError(LessonUploadError::DeletionFailed)),
-1 => Err(Error::LessonUploadError(LessonUploadError::WrongPassword)),
0 => Err(Error::LessonUploadError(
LessonUploadError::UnknownServerError,
)),
1 => Ok(()),
_ => Err(Error::LessonUploadError(LessonUploadError::Unknown)),
},
Err(e) => Err(Error::LessonUploadError(LessonUploadError::Network(
e.to_string(),
))),
}
}
}
pub async fn get_lessons(account: &Account) -> Result<Vec<Lesson>, Error> {
let client = &account.client;
let unix_time = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_millis();
match client
.get(URL::BASE.to_owned() + &format!("meinunterricht.php?cacheBreaker={}", unix_time))
.send()
.await
{
Ok(response) => {
match response.text().await {
Ok(response) => {
let response =
decrypt_lanis_encoded_tags(&response, &account.key_pair.public_key_string)
.await;
let document = Html::parse_document(&response);
let lesson_folders_selector = Selector::parse("#mappen").unwrap();
let row_selector = Selector::parse(".row").unwrap();
let h2_selector = Selector::parse("h2").unwrap();
let button_selector = Selector::parse("div.btn-group > button").unwrap();
let link_selector = Selector::parse("a.btn.btn-primary").unwrap();
if let Some(lesson_folders) = document.select(&lesson_folders_selector).next() {
if let Some(row) = lesson_folders.select(&row_selector).next() {
let mut lessons = Vec::new();
for lesson in row.child_elements() {
if let Some(url_element) = lesson.select(&link_selector).next() {
let url = url_element.value().attr("href").unwrap().to_string();
let id = url
.split("id=")
.nth(1)
.unwrap()
.to_string()
.parse::<i32>()
.unwrap();
let name = lesson
.select(&h2_selector)
.next()
.unwrap()
.text()
.collect::<String>()
.trim()
.to_string();
let teacher: String = lesson
.select(&button_selector)
.next()
.and_then(|btn| btn.value().attr("title"))
.map(|s| s.to_string())
.unwrap();
let teacher: String =
teacher.split(" (").next().unwrap().to_string();
lessons.push(Lesson {
id,
url,
name,
teacher,
teacher_short: None,
attendances: BTreeMap::new(),
entry_latest: None,
entries: None,
marks: None,
exams: None,
})
}
}
// Get latest lesson entry
let school_classes_selector = Selector::parse("tr.printable").unwrap();
let school_classes = document.select(&school_classes_selector);
for school_class in school_classes {
fn collect_text(
element_ref: Option<ElementRef>,
) -> Result<String, ()> {
match element_ref {
Some(element_ref) => {
let s = element_ref
.text()
.collect::<String>()
.trim()
.to_string();
Ok(s)
}
None => Err(()),
}
}
let topic_title_selector = Selector::parse(".thema").unwrap();
let topic_title =
collect_text(school_class.select(&topic_title_selector).next())
.unwrap_or("".to_string());
if topic_title.is_empty() {
continue;
}
let teacher_short_selector = Selector::parse(
".teacher .btn.btn-primary.dropdown-toggle.btn-xs",
)
.unwrap();
let teacher_short = collect_text(
school_class.select(&teacher_short_selector).next(),
)
.unwrap_or("".to_string());
let topic_date_selector = Selector::parse(".datum").unwrap();
let topic_date =
collect_text(school_class.select(&topic_date_selector).next())
.unwrap_or("".to_string());
let topic_date =
date_time_string_to_datetime(topic_date.as_str(), "02:00:00")
.map_err(|e| {
Error::DateTime(format!(
"failed to convert date to DateTime '{:?}'",
e
))
})?
.to_utc();
let course_url_selector = Selector::parse("td>h3>a").unwrap();
let course_url = school_class
.select(&course_url_selector)
.next()
.map(|x| {
x.value()
.attr("href")
.unwrap()
.to_string()
.trim()
.to_string()
})
.unwrap_or("".to_string());
let file_count_selector = Selector::parse(".file").unwrap();
let file_count: i32 =
school_class.select(&file_count_selector).count() as i32;
let entry_id = school_class
.value()
.attr("data-entry")
.unwrap_or("")
.parse::<i32>()
.unwrap();
let homework_selector = Selector::parse(".homework").unwrap();
let homework =
school_class.select(&homework_selector).next().map(|_| {
let description_selector =
Selector::parse(".realHomework").unwrap();
let description = school_class
.select(&description_selector)
.next()
.unwrap()
.text()
.collect::<String>()
.trim()
.to_string();
let completed = school_class
.select(&Selector::parse(".undone").unwrap())
.next()
.is_none();
Homework {
description,
completed,
}
});
for lesson in lessons.iter_mut() {
if lesson.url == course_url.to_owned() {
lesson.entry_latest = Option::from(LessonEntry {
id: entry_id.to_owned(),
date: topic_date.to_owned(),
school_hours: vec![-1],
title: topic_title.to_owned(),
details: None,
homework: homework.clone(),
attachments: None,
attachment_number: file_count,
uploads: None,
});
lesson.teacher_short = Some(teacher_short.to_owned());
}
}
}
let attendance_selector = Selector::parse("#anwesend").unwrap();
let thead_selector = Selector::parse("thead > tr").unwrap();
let tbody_selector = Selector::parse("tbody > tr").unwrap();
let link_selector = Selector::parse("a").unwrap();
let attendance_element =
document.select(&attendance_selector).next().unwrap();
let thead_element =
attendance_element.select(&thead_selector).next().unwrap();
let keys: Vec<String> = thead_element
.select(&Selector::parse("th").unwrap())
.map(|el| el.text().collect::<String>().trim().to_string())
.collect();
for row in attendance_element.select(&tbody_selector) {
let mut text_elements: Vec<String> = vec![];
let mut attendances: BTreeMap<String, String> = BTreeMap::new();
for element in row.child_elements() {
if let Some(attr) = element.attr("class") {
if attr.contains("hidden")
&& attr.contains("hidden_encoded")
{
continue;
}
}
text_elements.push(
element.text().collect::<String>().trim().to_string(),
);
}
for (i, key) in keys.iter().enumerate() {
let key_lower = key.to_lowercase();
let value =
text_elements.get(i).unwrap_or(&"".to_string()).clone();
if ["kurs", "lehrkraft"].contains(&key_lower.as_str()) {
continue;
}
let mut value = value
.lines()
.skip(1)
.next()
.unwrap_or("")
.trim()
.to_string();
if value.is_empty() {
value = "0".to_string();
}
attendances.insert(key_lower, value);
}
if let Some(hyperlink) = row.select(&link_selector).next() {
let course_url = hyperlink.value().attr("href").unwrap_or("");
for lesson in &mut lessons {
if course_url.contains(&lesson.id.to_string()) {
lesson.attendances = attendances;
break;
}
}
}
}
Ok(lessons)
} else {
Err(Error::Parsing(
"Failed to select rows from lesson folders".to_string(),
))
}
} else {
Err(Error::Parsing(
"Failed to select lesson folders".to_string(),
))
}
}
Err(e) => Err(Error::Parsing(format!(
"Failed converting response into text: {}",
e
))),
}
}
Err(e) => Err(Error::Network(format!(
"Failed to fetch lessons from '{}?cacheBreaker={}':\n{}",
URL::BASE,
unix_time,
e
))),
}
}