-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
397 lines (325 loc) · 14.1 KB
/
index.ts
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
import https from 'https'
import iso8859_15 from 'iso-8859-15'
const dafaultParameter = Object.freeze({
hostname: "ods.fh-dortmund.de",
headers: Object.freeze({
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:64.0) Gecko/20100101 Firefox/64.0'
})
})
const mergeOptionObjects = (custom, def = dafaultParameter) => {
const options = { ...def, ...custom };
if (!options.headers && def.headers)
options.headers = def.headers
return options;
}
function makeRequest(origOptions, body = undefined, transformToString = true, replaceRNtoN = true): Promise<{
statusCode: string,
responseHeader: string,
responseBody: string
}> {
const options = mergeOptionObjects(origOptions, dafaultParameter);
return new Promise((res, rej) => {
const req = https.request(options);
req.on('response', response => {
const contentType = response.headers['content-type'];
const isText = contentType.startsWith('text/');
let chunks = [];
response.on('data', chunk => {
chunks[chunks.length] = chunk;
});
response.on('end', () => {
const chuncBuffer = Buffer.concat(chunks);
let data;
if (isText && transformToString) {
let stringRepresentation = chuncBuffer.toString('utf8');
if (stringRepresentation.indexOf('<meta http-equiv="Content-type" content="text/html; charset=ISO-8859-15">') != -1)
stringRepresentation = iso8859_15.decode(chuncBuffer.toString('binary'));
if (replaceRNtoN)
stringRepresentation = stringRepresentation.replace(/\r\n/g, '\n');
data = stringRepresentation;
} else
data = chuncBuffer;
res({
statusCode: response.statusCode,
responseHeader: response.headers,
responseBody: data
});
})
});
req.on('error', err => {
rej(err);
});
req.end(typeof body == "string" || body instanceof Buffer ? body : undefined);
});
}
export interface GradesSummaryEntry {
/** the id of the entry (exam) */
id: string,
/** the displayed name of the exam */
name: string,
/** the type e.g. "Summe Leistungspunkte" */
type: string,
/** the date or semester on / in which this exam was taken */
dateSemester: string,
/** the examiner who held the course / exam */
examiner: string,
/** the recieved grade (e.g. "2,3") */
grade: string,
/** the European Credit Transfer System credits recieved for this exam */
ects: string,
/** the status of this exam ("PV, Prüfung vorhanden" | "BE, bestanden") */
status: string,
/** an optional note attached to this exam */
note: string
}
export interface GradesEntry {
/** the id of the entry (exam) */
id: string,
/** the displayed name of the exam */
name: string,
/** the type e.g. "Modulprüfung" | "Prüfgsleistg in Lehrveran" */
type: string,
/** the date or semester on / in which this exam was taken (this will be an date dd.mm.yy for type "Modulprüfung" and YYYYH (H = 1 | 2 which half of the year) for "Prüfgsleistg in Lehrveran") */
dateSemester: string,
/** the examiner who held the course / exam ("Secondname, Firstname") */
examiner: string,
/** the recieved grade (e.g. "2,3"), this field will be "" if the status is "AN, angemeldet" */
grade: string,
/** the European Credit Transfer System credits recieved for this exam, this field will be "" if the status is "AN, angemeldet" */
ects: string,
/** the status of this exam ("AN, angemeldet" | "BE, bestanden" | ...) */
status: string,
/** an optional note attached to this exam */
note: string
}
export interface MetaInformation {
/** the current targeted degree e.g. "84, Bachelor" */
degree: string,
/** the current major e.g. "B13, Software- und Systemtechnik (dual)" */
major: string,
/** the specialisation of the major */
areaOfSpecialisation: string,
/** the year in which the applying regulation was specified */
examRegulation: string,
/** the kind of studen e.g. "Haupthörer" */
status: string,
/** the title of the student e.g. "Herr" */
title: string,
/** the full name of the student */
fullName: string,
/** the street (and house number) of the student */
street: string,
/** the zip code and the town */
zipTown: string,
/** the date the present information was generated (d-m-yy e.g. "25.4.18") */
dateOfGeneration: string,
/** the matriculation number */
matriculationNumber: string,
/** the date of birt of the student (d-m-yy e.g. "2.10.90") */
dateOfBirth: string,
/** the town this student was born in */
birthTown: string,
/** the semester this student is currently in */
semester: string
}
/**
* This class represents an session on the ods plattform and enables the access to data provided by the website.
*/
export class ODSConnection {
/**
* The currently used session id to authenticate the user on the webpage
*/
private sessionId: string;
/**
* The cache timeout in milliseconds, please the description in the README
*/
public cacheTimeout: number = 6000000; // 100 minutes cache timeout
private _cachedGradesPage: {
time?: number,
body?: string,
gradesSummary?: GradesSummaryEntry[],
grades?: GradesEntry[],
meta?: MetaInformation
} = {};
/**
* You should not create an instance yourself! Use the login methode instead.
*/
private constructor(sessionId: string) {
this.sessionId = sessionId;
}
/**
* Clears the current cache, this will force the next call of one of the three get methodes to pull a new version of the html page.
*/
public clearCache(): void {
this._cachedGradesPage = {};
}
/**
* Check wether the item is cached or not.
*/
private _hasItemInCache(item: string): boolean {
return item in this._cachedGradesPage;
}
/**
* Gets the html page of the ods overwiev page
*/
private async _getGradesPage(): Promise<string> {
const now = Date.now();
if (!this._hasItemInCache('body') || this._cachedGradesPage.time < (now - this.cacheTimeout)) {
const { responseBody } = await makeRequest({
path: '/ods?Sicht=ExcS&ExcSicht=Notenspiegel&m=1&SIDD=' + this.sessionId
});
this._cachedGradesPage = {
body: responseBody,
time: now
};
}
return this._cachedGradesPage.body;
}
/**
* Gets the grade summary (lower table in the overview)
*/
public async getGradesSummary(useCache = true): Promise<GradesSummaryEntry[]> {
if (!useCache)
this.clearCache();
if (!this._hasItemInCache('gradesSummary')) {
const body = await this._getGradesPage();
const generalMatcher = /<table.*?<table.*?<table.*?<table.*?<table.*?<\/tr>(.*?)<\/table>/s;
const generalMatch = generalMatcher.exec(body);
if (generalMatch == null)
throw new Error('could not find the secion');
const tableRowMatcher = /<td>(.*?)<\/td>.+?<td>(.*?) <\/td>.+?<td>(.*?)<\/td>.+?<td>(.*?)<\/td>.+?<td>(.*?)<\/td>.+?<td>(.*?) <\/td>.+?<td align="right">(.*?)<\/td>.+?<td>(.*?)<\/td>.+?<td>(.*?) <\/td>/gs;
let matchObjects = [];
let match;
while ((match = tableRowMatcher.exec(generalMatch[1])) != null) {
matchObjects[matchObjects.length] = {
id: match[1],
name: match[2],
type: match[3],
dateSemester: match[4],
examiner: match[5],
grade: match[6],
ects: match[7],
status: match[8],
note: match[9]
};
}
this._cachedGradesPage.gradesSummary = matchObjects;
}
return [...this._cachedGradesPage.gradesSummary].map(v => ({ ...v }));
}
/**
* Gets the Meta information available in the ods system
*/
public async getMetaInformation(useCache = true): Promise<MetaInformation> {
if (!useCache)
this.clearCache();
if (!this._hasItemInCache('meta')) {
const body = await this._getGradesPage();
const meta = <MetaInformation>{};
{
const generalMatcher = /<table.*?<table.*?<table.*?<\/tr>(.*?)<\/table>/s;
const generalMatch = generalMatcher.exec(body);
if (generalMatch == null)
throw new Error('could not find the secion');
const tableRowMatcher = /<\/td>.*?<td>(.*?)<\/td>.*?<\/td>.*?<td>(.*?)<\/td>.*?<\/td>.*?<td>(.*?)<\/td>.*?<\/td>.*?<td>(.*?)<\/td>.*?<\/td>.*?<td>(?:\n )?(.*?)<\/td>.*?<\/td>.*?<td>(.*?)<\/td>/s;
const tableRowMatch = tableRowMatcher.exec(generalMatch[1]);
if (tableRowMatch == null)
throw new Error('could not find the meta information');
meta.degree = tableRowMatch[1];
meta.major = tableRowMatch[2];
meta.areaOfSpecialisation = tableRowMatch[3];
meta.examRegulation = tableRowMatch[4];
meta.status = tableRowMatch[5];
// meta.semester = tableRowMatch[6]; // will be setted by the next block
}
{
const generalMatcher = /<div style="text-align:left;float:left;">(.*)<div style="margin-top: 120px;"> <\/div>/s;
const generalMatch = generalMatcher.exec(body);
if (generalMatch == null)
throw new Error('could not find the secion');
const tableRowMatcher = /<b>(.*?)<\/b>.+?<b>(.*?)<\/b>.+?<b>(.*?)<\/b>.+?<b>(.*?)<\/b>.*?class="norm".*?<\/td>.*?<td>(.*?)<\/td>.*?<\/td>.*?<td>(.*?)<\/td>.*?<\/td>.*?<td>(.*?)<\/td>.*?<\/td>.*?<td>(.*?)<\/td>.*?<\/td>.*?<td>(.*?)<\/td>/s;
const tableRowMatch = tableRowMatcher.exec(generalMatch[1]);
if (tableRowMatch == null)
throw new Error('could not find the meta information');
meta.title = tableRowMatch[1];
meta.fullName = tableRowMatch[2];
meta.street = tableRowMatch[3];
meta.zipTown = tableRowMatch[4];
meta.dateOfGeneration = tableRowMatch[5];
meta.matriculationNumber = tableRowMatch[6];
meta.dateOfBirth = tableRowMatch[7];
meta.birthTown = tableRowMatch[8];
meta.semester = tableRowMatch[9];
}
this._cachedGradesPage.meta = meta;
}
return { ...this._cachedGradesPage.meta };
}
/**
* Gets the grades (upper table in the overview)
*/
public async getGrades(useCache = true): Promise<GradesEntry[]> {
if (!useCache)
this.clearCache();
if (!this._hasItemInCache('grades')) {
const body = await this._getGradesPage();
const generalMatcher = /Vermerk:<\/td>.+?<\/tr>(.+?)<\/table>/s;
const tableRowMatcher = /<td>(.*?)<\/td>.+?<td>(.*?) <\/td>.+?<td>(.*?)<\/td>.+?<td>(.*?)<\/td>.+?<td>(.*?)<\/td>.+?<td>(.*?) <\/td>.+?<td align="right">(.*?)<\/td>.+?<td>(.*?)<\/td>.+?<td>(.*?) <\/td>/gs;
const generalMatch = generalMatcher.exec(body);
if (generalMatch == null)
throw new Error('could not find the secion');
let matchObjects = [];
let match;
while ((match = tableRowMatcher.exec(generalMatch[1])) != null) {
matchObjects[matchObjects.length] = {
id: match[1],
name: match[2],
type: match[3],
dateSemester: match[4],
examiner: match[5],
grade: match[6],
ects: match[7],
status: match[8],
note: match[9]
};
}
this._cachedGradesPage.grades = matchObjects;
}
// copying the data to enable the user to manipulate it even if we cache it
return [...this._cachedGradesPage.grades].map(v => ({ ...v }));
}
/**
* Gets own endpoint (public ip adress of the current used network)
*/
private static async _getOwnEndpoint(): Promise<string> {
const matcher = /<input type=hidden name="RemoteEndPointIP" value="(.+?)">/;
const { responseBody } = await makeRequest({
path: '/ods'
});
const res = matcher.exec(responseBody);
return !res ? null : res[1];
}
/**
* Tries to login into the ods system with the given credentials. If the login succedes an ODSConnection instance will be returned, null otherwise.
*/
public static async login(username: string, password: string): Promise<null | ODSConnection> {
const remoteIP = await this._getOwnEndpoint();
const postBody = 'LIMod=&HttpRequest_PathFile=%2F&HttpRequest_Path=%2F&RemoteEndPointIP=' + remoteIP + '&User=' + encodeURIComponent(username) + '&PWD=' + encodeURIComponent(password) + '&x=0&y=0'
// some id like this 0x04FA76B1857DC2489FFD5520A82D349D
const matcher = /"https:\/\/dias\.fh-dortmund\.de\/ods\?Sicht=Menue&SIDD=(.+?)"/;
const { responseBody } = await makeRequest({
method: 'POST',
path: '/ods',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}, postBody);
const res = matcher.exec(responseBody);
const session = !res ? null : res[1];
if (session) {
return new ODSConnection(session);
} else {
return null;
}
}
}