-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuntis.js
274 lines (237 loc) · 6.71 KB
/
untis.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
/*
The api calls were reverse-engineered from the WebUntis Api Wrapper by SchoolUtils (https://github.com/SchoolUtils/WebUntis)
I am not in any way affiliated with Untis GmbH.
(c) Tobias Kendlbacher 2022 - MIT License
*/
const dotenv = require("dotenv");
dotenv.config();
let secrets = {
UNTIS_SCHOOL: process.env.UNTIS_SCHOOL,
UNTIS_USER: process.env.UNTIS_USER,
UNTIS_PASSWORD: process.env.UNTIS_PASSWORD,
UNTIS_URL: process.env.UNTIS_URL,
};
const untis_id = "ident";
let logged_in = false;
let untis_config;
let session_cookies;
let logindata;
/**
*
* @param {Date} date
* @returns {string}
*/
function convertToUntisDate(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()
);
}
/**
*
* @param {Date} date
* @returns {Date}
*/
function getNextMonday(date) {
let day = date.getDay();
let diff = date.getDate() - day + (day == 0 ? -6 : 1);
return new Date(date.setDate(diff));
}
/**
* Will use {@link secrets} as default
* @param {string} school
* @param {string} username
* @param {string} password
* @param {string} baseurl
*/
async function login(
school = secrets.UNTIS_SCHOOL,
username = secrets.UNTIS_USER,
password = secrets.UNTIS_PASSWORD,
baseurl = secrets.UNTIS_URL,
) {
if (logged_in) console.warn("Call to login even though already logged in");
let response = await fetch(
baseurl + "/WebUntis/jsonrpc.do?school=" + school,
{
method: "POST",
body: JSON.stringify({
id: untis_id,
method: "authenticate",
params: {
user: username,
password: password,
client: untis_id,
},
jsonrpc: "2.0",
}),
},
);
let res = await response.json();
if (res.data && res.data.error) throw new Error(res.data.error.message);
logindata = res;
let rheaders;
if (response?.headers != null) {
rheaders = response.headers
.get("set-cookie")
.split(";")
.reduce((prev, curr) => {
let kv = curr.trim().split("=");
prev[kv[0]] = kv[1] || undefined;
return prev;
}, {});
} else {
rheaders = {};
throw new Error("No response headers");
}
// Convert the response headers from an unusable string worm to a dict
let cookies = [];
cookies.push(`JSESSIONID=${rheaders["JSESSIONID"]}`);
cookies.push(
'schoolname="_' + Buffer.from(school).toString("base64") + '"',
);
session_cookies = cookies.join(";");
const config = await (
await fetch(`${baseurl}/WebUntis/api/app/config`, {
headers: { cookie: session_cookies },
})
).json();
// write variable to file
// fs.writeFileSync("config_nogit.json", JSON.stringify(config, null, 4));
logged_in = true;
untis_config = config;
return;
}
/**
* Logs out of the current session
* @param {string} school The school name to pass to the api
*/
async function logout(
school = secrets.UNTIS_SCHOOL,
baseurl = secrets.UNTIS_URL,
) {
if (!logged_in) console.warn("Call to logout even though not logged in");
if (!session_cookies) throw new Error("Not logged in");
await fetch(`${baseurl}/WebUntis/jsonrpc.do?school=${school}`, {
method: "POST",
body: JSON.stringify({
id: untis_id,
method: "logout",
params: {},
jsonrpc: "2.0",
}),
headers: {
cookie: session_cookies,
},
});
logged_in = false;
session_cookies = undefined; // Clear session cookies, as they are no longer valid
logindata = undefined;
}
/**
* @see {@link https://webuntis.noim.me/classes/WebUntis.html#getExamsForRange getExamsForRange - WebUntis API Docs}
*
* @param {Date} startDate
* @param {Date | null} endDate
* @param {string} baseurl Defaults to {@link secrets.UNTIS_URL}
* @param {string} cookies
*
* @returns {object}
*/
async function getExamsBetween(
startDate,
endDate = null,
baseurl = secrets.UNTIS_URL,
cookies = session_cookies,
) {
if (!session_cookies) throw new Error("Not logged in");
return await (
await fetch(
encodeURI(
`${baseurl}/WebUntis/api/exams?startDate=${convertToUntisDate(
startDate,
)}${
endDate == null
? "&endDate=" + convertToUntisDate(endDate)
: ""
}`,
),
{
headers: {
cookie: session_cookies,
},
},
)
).json();
}
/**
* @param {Date} date
* @returns {string}
*/
async function getWeeklyTimetableICAL(
date,
baseurl = secrets.UNTIS_URL,
cookies = session_cookies,
) {
// https://asopo.webuntis.com/WebUntis/Ical.do?elemType=5&elemId=5551&rpt_sd=2023-03-20
if (!session_cookies) throw new Error("Not logged in");
return await (
await fetch(
encodeURI(
`${baseurl}/WebUntis/Ical.do?elemType=5&elemId=${
logindata.result.personId
}&rpt_sd=${date.toISOString().split("T")[0]}`,
),
{
headers: {
cookie: session_cookies,
},
},
)
).text();
}
async function getWeeklyTimetable(
date,
baseurl = secrets.UNTIS_URL,
cookies = session_cookies,
) {
if (!session_cookies) throw new Error("Not logged in");
return await (
await fetch(
encodeURI(
`${baseurl}/WebUntis/api/public/timetable/weekly/data?elementType=5&elementId=${
logindata.result.personId
}&date=${date.toISOString().split("T")[0]}&formatId=3`,
),
{
headers: {
cookie: session_cookies,
},
},
)
).json();
}
async function main() {
await login();
// console.log(JSON.stringify(await getExamsBetween(new Date(), new Date(new Date().setMonth(11))), null, 2));
// console.log(JSON.stringify(await getWeeklyTimetable(new Date()), null, 2));
logout(secrets.UNTIS_SCHOOL);
}
if (require.main === module) {
main();
}
module.exports = {
login,
logout,
getExamsBetween,
getWeeklyTimetable,
getWeeklyTimetableICAL,
util: {
getNextMonday,
convertToUntisDate,
},
};