-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathindex.js
1075 lines (1006 loc) · 38.3 KB
/
index.js
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
const axios = require('axios');
const CookieBuilder = require('cookie');
const Base64 = require('./Base64');
const find = require('lodash.find');
const { parse, startOfDay, format } = require('date-fns');
/**
* WebUntis API Class
*/
class WebUntis {
/**
*
* @constructor
* @param {string} school The school identifier
* @param {string} username
* @param {string} password
* @param {string} baseurl Just the host name of your WebUntis (Example: mese.webuntis.com)
* @param {string} [identity="Awesome"] A identity like: MyAwesomeApp
* @param {boolean} [disableUserAgent=false] If this is true, axios will not send a custom User-Agent
*/
constructor(school, username, password, baseurl, identity = 'Awesome', disableUserAgent = false) {
this.school = school;
this.schoolbase64 = '_' + Base64.btoa(this.school);
this.username = username;
this.password = password;
this.baseurl = 'https://' + baseurl + '/';
this.cookies = [];
this.id = identity;
this.sessionInformation = {};
this.anonymous = false;
const additionalHeaders = {};
if (!disableUserAgent) {
additionalHeaders['User-Agent'] =
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.79 Safari/537.36';
}
this.axios = axios.create({
baseURL: this.baseurl,
maxRedirects: 0,
headers: {
'Cache-Control': 'no-cache',
Pragma: 'no-cache',
'X-Requested-With': 'XMLHttpRequest',
...additionalHeaders,
},
validateStatus: function (status) {
return status >= 200 && status < 303; // default
},
});
}
/**
* Logout the current session
* @returns {Promise<boolean>}
*/
async logout() {
await this.axios({
method: 'POST',
url: `/WebUntis/jsonrpc.do`,
params: {
school: this.school,
},
data: {
id: this.id,
method: 'logout',
params: {},
jsonrpc: '2.0',
},
});
this.sessionInformation = null;
return true;
}
/**
* Login with your credentials
*
* **Notice: The server may revoke this session after less than 10min of idle.**
*
* *Untis says in the official docs:*
* > An application should always logout as soon as possible to free system resources on the server.
* @returns {Promise<Object>}
*/
async login() {
const response = await this.axios({
method: 'POST',
url: `/WebUntis/jsonrpc.do`,
params: {
school: this.school,
},
data: {
id: this.id,
method: 'authenticate',
params: {
user: this.username,
password: this.password,
client: this.id,
},
jsonrpc: '2.0',
},
});
if (typeof response.data !== 'object') throw new Error('Failed to parse server response.');
if (!response.data.result) throw new Error('Failed to login. ' + JSON.stringify(response.data));
if (response.data.result.code) throw new Error('Login returned error code: ' + response.data.result.code);
if (!response.data.result.sessionId) throw new Error('Failed to login. No session id.');
this.sessionInformation = response.data.result;
return response.data.result;
}
/**
* Get the latest WebUntis Schoolyear
* @param {Boolean} [validateSession=true]
* @returns {Promise<{name: String, id: Number, startDate: Date, endDate: Date}>}
*/
async getLatestSchoolyear(validateSession = true) {
const data = await this._request('getSchoolyears', {}, validateSession);
data.sort((a, b) => {
const na = parse(a.startDate, 'yyyyMMdd', new Date());
const nb = parse(b.startDate, 'yyyyMMdd', new Date());
return nb - na;
});
if (!data[0]) throw new Error('Failed to receive school year');
return {
name: data[0].name,
id: data[0].id,
startDate: parse(data[0].startDate, 'yyyyMMdd', new Date()),
endDate: parse(data[0].endDate, 'yyyyMMdd', new Date()),
};
}
/**
* Get all WebUntis Schoolyears
* @param {Boolean} [validateSession=true]
* @returns {Promise<{name: String, id: Number, startDate: Date, endDate: Date}>}
*/
async getSchoolyears(validateSession = true) {
const data = await this._request('getSchoolyears', {}, validateSession);
data.sort((a, b) => {
const na = parse(a.startDate, 'yyyyMMdd', new Date());
const nb = parse(b.startDate, 'yyyyMMdd', new Date());
return nb - na;
});
if (!data[0]) throw new Error('Failed to receive school year');
return data.map((year) => {
return {
name: year.name,
id: year.id,
startDate: parse(year.startDate, 'yyyyMMdd', new Date()),
endDate: parse(year.endDate, 'yyyyMMdd', new Date()),
};
});
}
/**
* Get News Widget
* @param {Date} date
* @param {boolean} [validateSession=true]
* @returns {Promise<Object>} see index.d.ts NewsWidget
*/
async getNewsWidget(date, validateSession = true) {
if (validateSession && !(await this.validateSession())) throw new Error('Current Session is not valid');
const response = await this.axios({
method: 'GET',
url: `/WebUntis/api/public/news/newsWidgetData`,
params: {
date: this.convertDateToUntis(date),
},
headers: {
Cookie: this._buildCookies(),
},
});
if (typeof response.data.data !== 'object') throw new Error('Server returned invalid data.');
return response.data.data;
}
/**
* Get Inbox
* @returns {Promise<Object>}
*/
async getInbox(validateSession = true) {
this._checkAnonymous();
if (validateSession && !(await this.validateSession())) throw new Error('Current Session is not valid');
//first get JWT Token
if (typeof this.sessionInformation.jwt_token != 'string') await this._getJWT();
const response = await this.axios({
method: 'GET',
url: `/WebUntis/api/rest/view/v1/messages`,
headers: {
Authorization: `Bearer ${this.sessionInformation.jwt_token}`,
Cookie: this._buildCookies(),
},
});
if (typeof response.data !== 'object') throw new Error('Server returned invalid data.');
return response.data;
}
_checkAnonymous() {
if (this.anonymous) {
throw new Error('This method is not supported with anonymous login');
}
}
/**
*
* @returns {string}
* @private
*/
_buildCookies() {
let cookies = [];
cookies.push(CookieBuilder.serialize('JSESSIONID', this.sessionInformation.sessionId));
cookies.push(CookieBuilder.serialize('schoolname', this.schoolbase64));
return cookies.join('; ');
}
/**
* Get JWT Token
* @returns {Promise<String>}
*/
async _getJWT(validateSession = true) {
if (validateSession && !(await this.validateSession())) throw new Error('Current Session is not valid');
const response = await this.axios({
method: 'GET',
url: `/WebUntis/api/token/new`,
headers: {
//Authorization: `Bearer ${this._getToken()}`,
Cookie: this._buildCookies(),
},
});
if (typeof response.data !== 'string') throw new Error('Server returned invalid data.');
this.sessionInformation.jwt_token = response.data;
return response.data;
}
/**
* Checks if your current WebUntis Session is valid
* @returns {Promise<boolean>}
*/
async validateSession() {
if (!this.sessionInformation) return false;
const response = await this.axios({
method: 'POST',
url: `/WebUntis/jsonrpc.do`,
params: {
school: this.school,
},
headers: {
Cookie: this._buildCookies(),
},
data: {
id: this.id,
method: 'getLatestImportTime',
params: {},
jsonrpc: '2.0',
},
});
return typeof response.data.result === 'number';
}
/**
* Get the time when WebUntis last changed it's data
* @param {Boolean} [validateSession=true]
* @returns {Promise<Number>}
*/
async getLatestImportTime(validateSession = true) {
return this._request('getLatestImportTime', {}, validateSession);
}
/**
*
* @param id
* @param type
* @param startDate
* @param endDate
* @param validateSession
* @returns {Promise.<Array>}
* @private
*/
async _timetableRequest(id, type, startDate, endDate, validateSession = true) {
const additionalOptions = {};
if (startDate) {
additionalOptions.startDate = this.convertDateToUntis(startDate);
}
if (endDate) {
additionalOptions.endDate = this.convertDateToUntis(endDate);
}
return this._request(
'getTimetable',
{
options: {
id: new Date().getTime(),
element: {
id,
type,
},
...additionalOptions,
showLsText: true,
showStudentgroup: true,
showLsNumber: true,
showSubstText: true,
showInfo: true,
showBooking: true,
klasseFields: ['id', 'name', 'longname', 'externalkey'],
roomFields: ['id', 'name', 'longname', 'externalkey'],
subjectFields: ['id', 'name', 'longname', 'externalkey'],
teacherFields: ['id', 'name', 'longname', 'externalkey'],
},
},
validateSession
);
}
/**
* Get your own Timetable for the current day
* Note: You can't use this with anonymous login
* @param {Boolean} [validateSession=true]
* @returns {Promise<Array>}
*/
async getOwnTimetableForToday(validateSession = true) {
this._checkAnonymous();
return await this._timetableRequest(
this.sessionInformation.personId,
this.sessionInformation.personType,
null,
null,
validateSession
);
}
/**
* Get the timetable of today for a specific element.
* @param {number} id
* @param {WebUntisElementType} type
* @param {Boolean} [validateSession=true]
* @returns {Promise<Array>}
*/
async getTimetableForToday(id, type, validateSession = true) {
return await this._timetableRequest(id, type, null, null, validateSession);
}
/**
* Get your own Timetable for the given day
* Note: You can't use this with anonymous login
* @param {Date} date
* @param {Boolean} [validateSession=true]
* @returns {Promise.<Array>}
*/
async getOwnTimetableFor(date, validateSession = true) {
this._checkAnonymous();
return await this._timetableRequest(
this.sessionInformation.personId,
this.sessionInformation.personType,
date,
date,
validateSession
);
}
/**
* Get the timetable for a specific day for a specific element.
* @param {Date} date
* @param {number} id
* @param {WebUntisElementType} type
* @param {Boolean} [validateSession=true]
* @returns {Promise<Array>}
*/
async getTimetableFor(date, id, type, validateSession = true) {
return await this._timetableRequest(id, type, date, date, validateSession);
}
/**
* Get your own timetable for a given Date range
* Note: You can't use this with anonymous login
* @param {Date} rangeStart
* @param {Date} rangeEnd
* @param {Boolean} [validateSession=true]
* @returns {Promise.<Array>}
*/
async getOwnTimetableForRange(rangeStart, rangeEnd, validateSession = true) {
this._checkAnonymous();
return await this._timetableRequest(
this.sessionInformation.personId,
this.sessionInformation.personType,
rangeStart,
rangeEnd,
validateSession
);
}
/**
* Get the timetable for a given Date range for specific element
* @param {Date} rangeStart
* @param {Date} rangeEnd
* @param {number} id
* @param {WebUntisElementType} type
* @param {Boolean} [validateSession=true]
* @returns {Promise.<Array>}
*/
async getTimetableForRange(rangeStart, rangeEnd, id, type, validateSession = true) {
return await this._timetableRequest(id, type, rangeStart, rangeEnd, validateSession);
}
/**
* Get the Timetable of your class for today
* Note: You can't use this with anonymous login
* @param {Boolean} [validateSession=true]
* @returns {Promise<Array>}
*/
async getOwnClassTimetableForToday(validateSession = true) {
this._checkAnonymous();
return await this._timetableRequest(this.sessionInformation.klasseId, 1, null, null, validateSession);
}
/**
* Get the Timetable of your class for the given day
* Note: You can't use this with anonymous login
* @param {Date} date
* @param {Boolean} [validateSession=true]
* @returns {Promise.<Array>}
*/
async getOwnClassTimetableFor(date, validateSession = true) {
this._checkAnonymous();
return await this._timetableRequest(this.sessionInformation.klasseId, 1, date, date, validateSession);
}
/**
* Get the Timetable of your class for a given Date range
* Note: You can't use this with anonymous login
* @param {Date} rangeStart
* @param {Date} rangeEnd
* @param {boolean} [validateSession=true]
* @returns {Promise.<Array>}
*/
async getOwnClassTimetableForRange(rangeStart, rangeEnd, validateSession = true) {
this._checkAnonymous();
return await this._timetableRequest(this.sessionInformation.klasseId, 1, rangeStart, rangeEnd, validateSession);
}
/**
*
* @param {Date} rangeStart
* @param {Date} rangeEnd
* @param {boolean} [validateSession=true]
* @returns {Promise.<Array>}
*/
async getHomeWorksFor(rangeStart, rangeEnd, validateSession = true) {
if (validateSession && !(await this.validateSession())) throw new Error('Current Session is not valid');
const response = await this.axios({
method: 'GET',
url: `/WebUntis/api/homeworks/lessons`,
params: {
startDate: this.convertDateToUntis(rangeStart),
endDate: this.convertDateToUntis(rangeEnd),
},
headers: {
Cookie: this._buildCookies(),
},
});
if (typeof response.data.data !== 'object') throw new Error('Server returned invalid data.');
if (!response.data.data['homeworks']) throw new Error("Data object doesn't contains homeworks object.");
return response.data.data;
}
/**
* Converts the untis date string format to a normal JS Date object
* @param {string} date Untis date string
* @param {Date} [baseDate=new Date()] Base date. Default beginning of current day
* @returns {Date}
* @static
*/
static convertUntisDate(date, baseDate = startOfDay(new Date())) {
if (typeof date !== 'string') date = `${date}`;
return parse(date, 'yyyyMMdd', baseDate);
}
/**
* Convert a untis time string to a JS Date object
* @param {string|number} time Untis time string
* @param {Date} [baseDate=new Date()] Day used as base for the time. Default: Current date
* @returns {Date}
* @static
*/
static convertUntisTime(time, baseDate = new Date()) {
if (typeof time !== 'string') time = `${time}`;
return parse(time, 'Hmm', baseDate);
}
/**
* Get all known Subjects for the current logged in user
* @param {boolean} [validateSession=true]
* @returns {Promise.<Array>}
*/
async getSubjects(validateSession = true) {
return await this._request('getSubjects', {}, validateSession);
}
/**
* Get the timegrid of current school
* @param {boolean} [validateSession=true]
* @returns {Promise.<Array>}
*/
async getTimegrid(validateSession = true) {
return await this._request('getTimegridUnits', {}, validateSession);
}
/**
*
* @param {Date} rangeStart
* @param {Date} rangeEnd
* @param {boolean} [validateSession=true]
* @returns {Promise.<void>}
*/
async getHomeWorkAndLessons(rangeStart, rangeEnd, validateSession = true) {
if (validateSession && !(await this.validateSession())) throw new Error('Current Session is not valid');
const response = await this.axios({
method: 'GET',
url: `/WebUntis/api/homeworks/lessons`,
params: {
startDate: this.convertDateToUntis(rangeStart),
endDate: this.convertDateToUntis(rangeEnd),
},
headers: {
Cookie: this._buildCookies(),
},
});
if (typeof response.data.data !== 'object') throw new Error('Server returned invalid data.');
if (!response.data.data['homeworks']) throw new Error("Data object doesn't contains homeworks object.");
return response.data.data;
}
/**
* Get Exams for range
* @param {Date} rangeStart
* @param {Date} rangeEnd
* @param {Number} klasseId
* @param {boolean} withGrades
* @param {boolean} [validateSession=true]
* @returns {Promise.<void>}
*/
async getExamsForRange(rangeStart, rangeEnd, klasseId = -1, withGrades = false, validateSession = true) {
if (validateSession && !(await this.validateSession())) throw new Error('Current Session is not valid');
const response = await this.axios({
method: 'GET',
url: `/WebUntis/api/exams`,
params: {
startDate: this.convertDateToUntis(rangeStart),
endDate: this.convertDateToUntis(rangeEnd),
klasseId: klasseId,
withGrades: withGrades,
},
headers: {
Cookie: this._buildCookies(),
},
});
if (typeof response.data.data !== 'object') throw new Error('Server returned invalid data.');
if (!response.data.data['exams']) throw new Error("Data object doesn't contains exams object.");
return response.data.data['exams'];
}
/**
* Get the timetable for the current week for a specific element from the web client API.
* @param {Date} date one date in the week to query
* @param {number} id element id
* @param {WebUntisElementType} type element type
* @param {Number} [formatId=1] set to 1 to include teachers, 2 omits the teachers in elements response
* @param {Boolean} [validateSession=true]
* @returns {Promise<WebAPITimetable[]>}
*/
async getTimetableForWeek(date, id, type, formatId = 1, validateSession = true) {
if (validateSession && !(await this.validateSession())) throw new Error('Current Session is not valid');
const response = await this.axios({
method: 'GET',
url: `/WebUntis/api/public/timetable/weekly/data`,
params: {
elementType: type,
elementId: id,
date: format(date, 'yyyy-MM-dd'),
formatId: formatId,
},
headers: {
Cookie: this._buildCookies(),
},
});
if (typeof response.data.data !== 'object') throw new Error('Server returned invalid data.');
if (response.data.data.error) {
/* known codes:
* - ERR_TTVIEW_NOTALLOWED_ONDATE
*/
const err = new Error("Server responded with error");
err.code = response.data.data.error?.data?.messageKey;
throw err;
}
if (!response.data.data.result?.data?.elementPeriods?.[id])
throw new Error('Invalid response');
const data = response.data.data.result.data;
const formatElements = (elements, { byType }) => {
const filteredElements = elements.filter((element) => element.type === byType);
return filteredElements.map((element) => ({
...element,
element: data.elements.find(
(dataElement) => dataElement.type === byType && dataElement.id === element.id
),
}));
};
const timetable = data.elementPeriods[id].map((lesson) => ({
...lesson,
classes: formatElements(lesson.elements, { byType: WebUntis.TYPES.CLASS }),
teachers: formatElements(lesson.elements, { byType: WebUntis.TYPES.TEACHER }),
subjects: formatElements(lesson.elements, { byType: WebUntis.TYPES.SUBJECT }),
rooms: formatElements(lesson.elements, { byType: WebUntis.TYPES.ROOM }),
students: formatElements(lesson.elements, { byType: WebUntis.TYPES.STUDENT }),
}));
return timetable;
}
/**
* Get the timetable for the current week for the current element from the web client API.
* @param {Date} date one date in the week to query
* @param {Number} [formatId=1] set to 1 to include teachers, 2 omits the teachers in elements response
* @param {Boolean} [validateSession=true]
* @returns {Promise<WebAPITimetable[]>}
*/
async getOwnTimetableForWeek(date, formatId = 1, validateSession = true) {
this._checkAnonymous();
return await this.getTimetableForWeek(
date,
this.sessionInformation.personId,
this.sessionInformation.personType,
formatId,
validateSession
);
}
/**
* Get all known teachers by WebUntis
* @param {boolean} [validateSession=true]
* @returns {Promise.<Array>}
*/
async getTeachers(validateSession = true) {
return await this._request('getTeachers', {}, validateSession);
}
/**
* Get all known students by WebUntis
* @param {boolean} [validateSession=true]
* @returns {Promise.<Array>}
*/
async getStudents(validateSession = true) {
return await this._request('getStudents', {}, validateSession);
}
/**
* Get all known rooms by WebUntis
* @param {boolean} [validateSession=true]
* @returns {Promise.<Array>}
*/
async getRooms(validateSession = true) {
return await this._request('getRooms', {}, validateSession);
}
/**
* Get all classes known by WebUntis
* @param {boolean} [validateSession=true]
* @param {number} schoolyearId
* @returns {Promise.<Array>}
*/
async getClasses(validateSession = true, schoolyearId) {
const data = typeof schoolyearId !== 'number' ? {} : { schoolyearId };
return await this._request('getKlassen', data, validateSession);
}
/**
* Get all departments known by WebUntis
* @param {boolean} [validateSession=true]
* @returns {Promise.<Array>}
*/
async getDepartments(validateSession = true) {
return await this._request('getDepartments', {}, validateSession);
}
/**
* Get all holidays known by WebUntis
* @param {boolean} [validateSession=true]
* @returns {Promise.<Array>}
*/
async getHolidays(validateSession = true) {
return await this._request('getHolidays', {}, validateSession);
}
/**
* Get all status data known by WebUntis
* @param {boolean} [validateSession=true]
* @returns {Promise.<Array>}
*/
async getStatusData(validateSession = true) {
return await this._request('getStatusData', {}, validateSession);
}
/**
* Convert a JS Date Object to a WebUntis date string
* @param {Date} date
* @returns {String}
*/
convertDateToUntis(date) {
return (
date.getFullYear().toString() +
(date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1).toString() +
(date.getDate() < 10 ? '0' + date.getDate() : date.getDate()).toString()
);
}
/**
* Make a JSON RPC Request with the current session
* @param {string} method
* @param {Object} [parameter={}]
* @param {string} [url='/WebUntis/jsonrpc.do?school=SCHOOL']
* @param {boolean} [validateSession=true] Whether the session should be checked first
* @returns {Promise.<any>}
* @private
*/
async _request(method, parameter = {}, validateSession = true, url = `/WebUntis/jsonrpc.do`) {
if (validateSession && !(await this.validateSession())) throw new Error('Current Session is not valid');
const response = await this.axios({
method: 'POST',
url: url,
params: {
school: this.school,
},
headers: {
Cookie: this._buildCookies(),
},
data: {
id: this.id,
method: method,
params: parameter,
jsonrpc: '2.0',
},
});
if (!response.data.result) throw new Error("Server didn't return any result.");
if (response.data.result.code) throw new Error('Server returned error code: ' + response.data.result.code);
return response.data.result;
}
/**
* Returns all the Lessons where you were absent including the excused one!
* @param {Date} rangeStart
* @param {Date} rangeEnd
* @param {Integer} [excuseStatusId=-1]
* @param {boolean} [validateSession=true]
* @returns {Promise<Absences>}
*/
async getAbsentLesson(rangeStart, rangeEnd, excuseStatusId = -1, validateSession = true) {
if (validateSession && !(await this.validateSession())) throw new Error('Current Session is not valid');
this._checkAnonymous();
const response = await this.axios({
method: 'GET',
url: `/WebUntis/api/classreg/absences/students`,
params: {
startDate: this.convertDateToUntis(rangeStart),
endDate: this.convertDateToUntis(rangeEnd),
studentId: this.sessionInformation.personId,
excuseStatusId: excuseStatusId,
},
headers: {
Cookie: this._buildCookies(),
},
});
if (response.data.data == null) throw new Error('Server returned no data!');
return response.data.data;
}
/**
* Returns a URL to a unique PDF of all the lessons you were absent
* @param {Date} rangeStart
* @param {Date} rangeEnd
* @param {boolean} [validateSession=true]
* @param {Integer} [excuseStatusId=-1]
* @param {boolean} [lateness=true]
* @param {boolean} [absences=true]
* @param {boolean} [excuseGroup=2]
* @returns {String} URL
*/
async getPdfOfAbsentLesson(
rangeStart,
rangeEnd,
validateSession = true,
excuseStatusId = -1,
lateness = true,
absences = true,
excuseGroup = 2
) {
if (validateSession && !(await this.validateSession())) throw new Error('Current Session is not valid');
this._checkAnonymous();
const response = await this.axios({
method: 'GET',
url: `/WebUntis/reports.do`,
params: {
name: 'Excuse',
format: 'pdf',
rpt_sd: this.convertDateToUntis(rangeStart),
rpt_ed: this.convertDateToUntis(rangeEnd),
excuseStatusId: excuseStatusId,
studentId: this.sessionInformation.personId,
withLateness: lateness,
withAbsences: absences,
execuseGroup: excuseGroup,
},
headers: {
Cookie: this._buildCookies(),
},
});
const res = response.data.data;
if (response.status != 200 || res.error) throw new Error('Server returned no data!');
const pdfDownloadURL =
this.baseurl + 'WebUntis/reports.do?' + 'msgId=' + res.messageId + '&' + res.reportParams;
return pdfDownloadURL;
}
}
class InternalWebuntisSecretLogin extends WebUntis {
constructor(school, username, password, baseurl, identity = 'Awesome', disableUserAgent = false) {
super(school, username, password, baseurl, identity, disableUserAgent);
}
async _otpLogin(token, username, time, skipSessionInfo = false) {
const url = `/WebUntis/jsonrpc_intern.do?m=getUserData2017&school=${this.school}&v=i2.2`;
const response = await this.axios({
method: 'POST',
url,
data: {
id: this.id,
method: 'getUserData2017',
params: [
{
auth: {
clientTime: time,
user: username,
otp: token,
},
},
],
jsonrpc: '2.0',
},
});
if (response.data && response.data.error)
throw new Error('Failed to login. ' + (response.data.error.message || ''));
if (
response.headers &&
response.headers['set-cookie'] &&
this._getCookieFromSetCookie(response.headers['set-cookie']) === false
)
throw new Error("Failed to login. Server didn't return a session id.");
const sessionId = this._getCookieFromSetCookie(response.headers['set-cookie']);
// Set session temporary
this.sessionInformation = {
sessionId: sessionId,
};
if (skipSessionInfo) return true;
// Get personId & personType
const appConfigUrl = `/WebUntis/api/app/config`;
const configResponse = await this.axios({
method: 'GET',
url: appConfigUrl,
headers: {
Cookie: this._buildCookies(),
},
});
if (typeof configResponse.data !== 'object' || typeof configResponse.data.data !== 'object')
throw new Error('Failed to fetch app config while login. data (type): ' + typeof response.data);
// Path -> data.loginServiceConfig.user.persons -> find person with id
if (
configResponse.data.data &&
configResponse.data.data.loginServiceConfig &&
configResponse.data.data.loginServiceConfig.user &&
!Number.isInteger(configResponse.data.data.loginServiceConfig.user.personId)
)
throw new Error('Invalid personId. personId: ' + configResponse.data.data.loginServiceConfig.user.personId);
const webUntisLoginServiceUser = configResponse.data.data.loginServiceConfig.user;
if (!Array.isArray(webUntisLoginServiceUser.persons))
throw new Error('Invalid person array. persons (type): ' + typeof webUntisLoginServiceUser.persons);
const person = find(webUntisLoginServiceUser.persons, {
id: configResponse.data.data.loginServiceConfig.user.personId,
});
if (!person) throw new Error('Can not find person in person array.');
if (!Number.isInteger(person.type)) throw new Error('Invalid person type. type (type): ' + person.type);
this.sessionInformation = {
sessionId: sessionId,
personType: person.type,
personId: configResponse.data.data.loginServiceConfig.user.personId,
};
// Get klasseId
try {
const dayConfigUrl = `/WebUntis/api/daytimetable/config`;
const dayConfigResponse = await this.axios({
method: 'GET',
url: dayConfigUrl,
headers: {
Cookie: this._buildCookies(),
},
});
if (typeof dayConfigResponse.data !== 'object' || typeof dayConfigResponse.data.data !== 'object')
throw new Error();
if (!Number.isInteger(dayConfigResponse.data.data.klasseId)) throw new Error();
this.sessionInformation = {
sessionId: sessionId,
personType: person.type,
personId: configResponse.data.data.loginServiceConfig.user.personId,
klasseId: dayConfigResponse.data.data.klasseId,
};
} catch (e) {
// klasseId is not important. This request can fail
}
return true;
}
/**
*
* @param {Array} setCookieArray
* @param {string} [cookieName="JSESSIONID"]
* @return {string|boolean}
* @private
*/
_getCookieFromSetCookie(setCookieArray, cookieName = 'JSESSIONID') {
if (!setCookieArray) return false;
for (let i = 0; i < setCookieArray.length; i++) {
const setCookie = setCookieArray[i];
if (!setCookie) continue;
let cookieParts = setCookie.split(';');
if (!cookieParts || !Array.isArray(cookieParts)) continue;
for (let cookie of cookieParts) {
cookie = cookie.trim();
cookie = cookie.replace(/;/gm, '');
const [Key, Value] = cookie.split('=');
if (!Key || !Value) continue;
if (Key === cookieName) return Value;
}
}
return false;
}
}
class WebUntisAnonymousAuth extends InternalWebuntisSecretLogin {
/**
*
* @param {string} school
* @param {string} baseurl
* @param {string} [identity='Awesome']
* @param {boolean} [disableUserAgent=false] If this is true, axios will not send a custom User-Agent
*/
constructor(school, baseurl, identity = 'Awesome', disableUserAgent = false) {
super(school, null, null, baseurl, identity, false, disableUserAgent);
this.username = '#anonymous#';
this.anonymous = true;
}
async login() {
// Check whether the school has public access or not
const url = `/WebUntis/jsonrpc_intern.do`;
const response = await this.axios({
method: 'POST',
url,
params: {
m: 'getAppSharedSecret',
school: this.school,
v: 'i3.5',
},
data: {
id: this.id,
method: 'getAppSharedSecret',
params: [
{
userName: '#anonymous#',
password: '',
},
],
jsonrpc: '2.0',
},
});
if (response.data && response.data.error)
throw new Error('Failed to login. ' + (response.data.error.message || ''));
// OTP never changes when using anonymous login
const otp = 100170;
const time = new Date().getTime();
return await this._otpLogin(otp, this.username, time, true);
}
}