-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
431 lines (378 loc) · 10.7 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
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
import { fetchAndParse, fetchRequest } from './utils/index.js';
import { CheckForToken } from './decorators/index.js';
import { Methods, userTypeFromString, UserTypes } from './enums/index.js';
import type {
Absence,
AbsencePermissions,
Assignment,
AssignmentInformation,
AssignmentResult,
BaseNotice,
Calendar,
CalendarObject,
LessonStatus,
LunchMenu,
NewsItem,
NoticeActionable,
NoticeActionableResponse,
NoticeLimit,
NoticeObject,
Schedule,
SchoolListInfo,
Token,
User
} from './types';
interface CustomRequestInit extends Omit<RequestInit, 'headers'> {
headers: {
appos: 'ios';
appversion: '2.3.14';
deviceid: 'node-schoolsoft';
appkey?: User['appKey'];
token?: Token['token'];
'Content-Type'?: 'application/json';
};
}
/**
* The SchoolSoft class, where all the magic happens.
*/
export class SchoolSoft {
/**
* Base URL of SchoolSoft for schools.
*/
public static readonly baseUrl = 'https://sms.schoolsoft.se';
public readonly baseFetchOptions: CustomRequestInit = {
headers: {
appos: 'ios',
appversion: '2.3.14',
// Value doesn't matter, but the key & value is needed.
deviceid: 'node-schoolsoft'
},
method: Methods.Get
};
public user: User;
/**
* Initializes the SchoolSoft class. Call the `login` method after initializing.
* @param username - The username of the account.
* @param password - The password of the account.
* @param school - The school of the account.
* @param [type] - The type of the account, the default is student.
*/
public constructor(
private readonly username: string,
private readonly password: string,
private readonly school: string,
private type: UserTypes = UserTypes.Student
) {}
public static getSchoolList() {
return fetchAndParse<SchoolListInfo[]>(`${this.baseUrl}/rest/app/schoollist/prod`);
}
private get defaultStartDate() {
return new Date(new Date().getFullYear() - (new Date().getMonth() < 6 ? 0 : 1), 7);
}
private get defaultEndDate() {
return new Date(new Date().getFullYear() + (new Date().getMonth() < 6 ? 1 : 0), 6);
}
private get url(): `${typeof SchoolSoft['baseUrl']}/${SchoolSoft['school']}` {
return `${SchoolSoft.baseUrl}/${this.school}`;
}
private get orgId() {
return this.user.orgs[0].orgId;
}
private restUrl(...path: Array<string | number>) {
return `${this.url}/rest/app/${path.join('/')}`;
}
private apiUrl(...path: Array<string | number>) {
return `${this.url}/api/${path.join('/')}`;
}
public async login() {
const body = new URLSearchParams();
body.set('identification', this.username);
body.set('verification', this.password);
// 4 is for mobile login which is what this API wrapper imitates the device as.
body.set('logintype', '4');
body.set('usertype', userTypeFromString(this.type).toString());
const options = { ...this.baseFetchOptions };
options.body = body;
options.method = Methods.Post;
this.user = await fetchAndParse<User>(this.restUrl('login'), options);
return this.getToken();
}
public async getToken() {
if (typeof this.user.appKey === 'undefined') {
throw new ReferenceError("Missing the user's app key, cannot fetch the token.");
}
const options = { ...this.baseFetchOptions };
options.headers.appkey = this.user.appKey;
const data = await fetchAndParse<Token>(this.restUrl('token'), options);
this.baseFetchOptions.headers.token = data.token;
return data;
}
public async setAppKey(appKey: User['appKey']) {
// @ts-expect-error: We only need `appKey` to be defined in the `user` object.
this.user = {
appKey
};
const token = await this.getToken();
this.user = await this.getUser();
this.user.appKey = appKey;
this.type = this.user.type;
return token;
}
/**
* Please use the `user` property instead of this function. This method exists because it's a known SchoolSoft route.
*/
@CheckForToken
public getUser() {
return fetchAndParse<User>(this.apiUrl('user', 'get'), this.baseFetchOptions);
}
@CheckForToken
public getLunchMenu() {
return fetchAndParse<LunchMenu[]>(
this.apiUrl('lunchmenus', this.type, this.orgId),
this.baseFetchOptions
);
}
@CheckForToken
public getSchedule() {
return fetchAndParse<Schedule[]>(
this.apiUrl('lessons', this.type, this.orgId),
this.baseFetchOptions
);
}
/**
* @param [start] - The starting week number (1-52).
* @param [end] - The ending week number (1-52).
*/
@CheckForToken
public getAbsences(start = 1, end = 52) {
return fetchAndParse<Absence[]>(
this.apiUrl('absences', this.type, this.orgId, start, end),
this.baseFetchOptions
);
}
@CheckForToken
public getAbsencePermissions() {
return fetchAndParse<AbsencePermissions>(
this.apiUrl('parameters', this.type, this.orgId),
this.baseFetchOptions
);
}
/**
* @param [start] - The starting date.
* @param [end] - The ending date.
*/
@CheckForToken
public getAssignments(start = this.defaultStartDate, end = this.defaultEndDate) {
return fetchAndParse<Assignment[]>(
this.apiUrl('notices', this.type, this.orgId, start.getTime(), end.getTime(), 'test'),
this.baseFetchOptions
);
}
/**
* @param id - The assignment's id.
*/
@CheckForToken
public getAssignmentInformation(id: Assignment['id']) {
return fetchAndParse<AssignmentInformation>(
this.apiUrl('tests', this.type, this.orgId, id, 0),
this.baseFetchOptions
);
}
/**
* @param id - The assignment id.
*/
@CheckForToken
public getAssignmentResult(id: Assignment['id']) {
return fetchAndParse<AssignmentResult>(this.apiUrl('news', this.type, this.orgId, id));
}
/**
* @param [start] - The starting date.
* @param [end] - The ending date.
*/
@CheckForToken
public getLessonStatuses(start = this.defaultStartDate, end = this.defaultEndDate) {
return fetchAndParse<LessonStatus[]>(
this.apiUrl(
'notices',
this.type,
this.orgId,
// Start & end timestamps are flipped for some reason in the API.
end.getTime(),
start.getTime(),
`lessonstatus${this.type}_1`
),
this.baseFetchOptions
);
}
/**
* @param [options] - The options for the types of calendar events to include.
* @param [start] - The starting date.
* @param [end] - The ending date.
*/
@CheckForToken
public getCalendar(
options: Array<CalendarObject> = ['calendar', 'schoolcalendar', 'privatecalendar'],
start = this.defaultStartDate,
end = this.defaultEndDate
) {
return fetchAndParse<Calendar[]>(
this.apiUrl(
'notices',
this.type,
this.orgId,
start.getTime(),
end.getTime(),
[...new Set(options)].join(',')
),
this.baseFetchOptions
);
}
/**
* @param [options] - The options for the types of notices to include.
* @param [start] - The starting week number (1-52).
* @param [end] - The ending week number (1-52).
*/
@CheckForToken
public getNoticesLimit(
options: Array<NoticeObject> = ['news', 'inquiry', 'teststudent', 'message'],
start = 0,
end = 52
) {
return fetchAndParse<NoticeLimit>(
this.apiUrl(
'notices',
this.type,
'limit',
this.orgId,
start,
end,
[...new Set(options)].join(',')
),
this.baseFetchOptions
);
}
@CheckForToken
public getNoticesActionable() {
return fetchAndParse<NoticeActionable[]>(
this.apiUrl('notices', this.type, 'actionable', this.orgId),
this.baseFetchOptions
);
}
/**
* @param [options] - The options for the types of notices to include.
* @param [start] - The starting week number (1-52).
* @param [end] - The ending week number (1-52).
*/
@CheckForToken
public getNoticesArchived(
options: Array<NoticeObject> = ['news', 'inquiry', 'teststudent', 'message'],
start = 0,
end = 52
) {
return fetchAndParse<NoticeLimit>(
this.apiUrl(
'notices',
this.type,
'limit',
'archived',
this.orgId,
start,
end,
[...new Set(options)].join(',')
),
this.baseFetchOptions
);
}
/**
* @param id - The news item's id.
*/
@CheckForToken
public getNewsItem(id: BaseNotice['id']) {
return fetchAndParse<NewsItem>(
this.apiUrl('news', this.type, this.orgId, id),
this.baseFetchOptions
);
}
/**
* @param id - The news item's id.
* @returns Whether the news item has been as archived.
*/
@CheckForToken
public setNoticeAsArchived(id: BaseNotice['id']) {
const options = { ...this.baseFetchOptions };
options.method = Methods.Put;
return fetchRequest(this.apiUrl('notices', this.type, 'archive', this.orgId, id), options);
}
/**
* @param id - The news item's id.
* @returns Whether the news item has been as unarchived.
*/
@CheckForToken
public setNoticeAsUnarchived(id: BaseNotice['id']) {
const options = { ...this.baseFetchOptions };
options.method = Methods.Put;
return fetchRequest(this.apiUrl('notices', this.type, 'unarchive', this.orgId, id), options);
}
/**
* @param id - The news item's id.
* @returns Whether the news item has been set as read.
*/
@CheckForToken
public setNoticeAsRead(id: BaseNotice['id']) {
return fetchRequest(
this.apiUrl('notices', this.type, 'read', this.orgId, id),
this.baseFetchOptions
);
}
/**
* @param id - The news item's id.
* @returns Whether the news item has been set as unread.
*/
@CheckForToken
public setNoticeAsUnread(id: BaseNotice['id']) {
return fetchRequest(
this.apiUrl('notices', this.type, 'unread', this.orgId, id),
this.baseFetchOptions
);
}
/**
* @param id - The news item's id.
* @param [responseText] - The text to send as a response.
* @returns Whether the actionable notice item has been set as confirmed.
*/
@CheckForToken
public setNoticeActionableAsConfirmed(
id: BaseNotice['id'],
responseText: NoticeActionableResponse['responseText'] = ''
) {
const options = { ...this.baseFetchOptions };
options.method = Methods.Post;
options.headers['Content-Type'] = 'application/json';
options.body = JSON.stringify({ responseText } as NoticeActionableResponse);
return fetchRequest(this.apiUrl('notices', this.type, 'confirm', this.orgId, id), options);
}
}
/**
* Initializes the SchoolSoft class and logs in. This is the recommended way of connecting/logging in.
* @returns The logged in SchoolSoft instance.
*/
export async function connect(...parameters: ConstructorParameters<typeof SchoolSoft>) {
const user = new SchoolSoft(...parameters);
await user.login();
return user;
}
/**
* Initializes the SchoolSoft class and logs in with the app key and school.
* @param appKey - The user's app key.
* @param school - The user's school.
* @returns The logged in SchoolSoft instance.
*/
export async function connectWithAppKeyAndSchool(
appKey: User['appKey'],
school: ConstructorParameters<typeof SchoolSoft>[2]
) {
const user = new SchoolSoft('', '', school);
await user.setAppKey(appKey);
return user;
}
export * from './enums/index.js';