This repository has been archived by the owner on Apr 10, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
/
sigaa-course-forum-student.ts
executable file
·540 lines (489 loc) · 13.1 KB
/
sigaa-course-forum-student.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
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
import { URL } from 'url';
import { FormData } from 'formdata-node';
import { Parser } from '@helpers/sigaa-parser';
import { File, FileData } from '@resources/sigaa-file';
import {
AbstractUpdatableResource,
UpdatableResource,
UpdatableResourceCallback
} from '@resources/updatable-resource';
import { HTTP } from '@session/sigaa-http';
import { SigaaForm, Page } from '@session/sigaa-page';
import { CourseResourcesFactory } from '@courses/sigaa-course-resources-factory';
import { UpdatableResourceData } from '@resources/sigaa-resource-manager';
/**
* Object that contains basic information about the class forum.
* @category Internal
*/
export interface ForumData extends UpdatableResourceData {
/**
* Title of the forum.
*/
title: string;
/**
* Id of the forum. This is unique
*/
id: string;
/**
* Form with parameters and url to load the forum page.
*/
form: SigaaForm;
/**
* creation date of the forum.
*/
creationDate?: Date;
/**
* Like 'Uma única discussão simples'
*/
forumType?: string;
/**
* Forum creator.
*/
author?: string;
/**
* Number of topics
*/
numOfTopics?: number;
}
/**
* @category Public
*/
export interface CourseForum extends UpdatableResource<ForumData> {
readonly type: 'forum';
/**
* If read monitoring is enabled.
*/
getFlagMonitorReading(): Promise<boolean>;
/**
* Number of topics
*/
getNumOfTopics(): Promise<number>;
/**
* Post topic in forum
* @param title title of topic
* @param body body of topic
* @param file buffer of file attachment
* @param notify if notify members
*/
postTopic(
title: string,
body: string,
file: string,
notify: boolean
): Promise<void>;
/**
* Post author
*/
getAuthor(): Promise<string>;
/**
* File attached to the forum.
*/
getFile(): Promise<File | undefined>;
/**
* Like 'Uma única discussão simples'
*/
getForumType(): Promise<string>;
readonly title: string;
/**
* creation date of the forum.
*/
getCreationDate(): Promise<Date>;
}
/**
* @category Internal
*/
export class SigaaCourseForum
extends AbstractUpdatableResource
implements CourseForum
{
/**
* Type of instance
*/
readonly type = 'forum';
/**
* Form with parameters and url to load the forum page.
*/
private _form!: SigaaForm;
/**
* Title of the forum.
*/
private _title!: string;
/**
* Number of topics
*/
private _numOfTopics?: number;
/**
* Forum creator.
*/
private _author?: string;
/**
* Like 'Uma única discussão simples'
*/
private _forumType?: string;
/**
* Description of the forum.
*/
private _description?: string;
/**
* Form to submit topics in the forum.
*/
private _submitTopicPageForm?: SigaaForm;
/**
* File attached to the forum.
*/
private _file?: File;
/**
* the forum id.
*/
private _id!: string;
/**
* If read monitoring is enabled.
*/
private _flagMonitorReading?: boolean;
/**
*
*/
private _fullForumPromise: Promise<void> | null = null;
/**
* creation date of the forum.
*/
private _creationDate?: Date;
constructor(
private http: HTTP,
private parser: Parser,
private courseResourcesFactory: CourseResourcesFactory,
forumOptions: ForumData,
updater: UpdatableResourceCallback
) {
super(forumOptions.instanceIndentifier, updater);
this.update(forumOptions);
}
update(forumOptions: ForumData): void {
this._title = forumOptions.title;
this._form = forumOptions.form;
this._id = forumOptions.id;
if (forumOptions.forumType !== undefined) {
this._forumType = forumOptions.forumType;
}
if (forumOptions.numOfTopics !== undefined) {
this._numOfTopics = forumOptions.numOfTopics;
}
if (forumOptions.author !== undefined) {
this._author = forumOptions.author;
}
}
/**
* Loads the forum page.
* @param retry
*/
private async getForumPage(retry = true): Promise<void> {
try {
const page = await this.http.post(
this._form.action.href,
this._form.postValues
);
this.parseForumTable(page);
this.parseSubmitPageForm(page);
} catch (err) {
if (retry) {
await this.updateInstance();
return this.getForumPage(false);
} else {
throw err;
}
}
}
/**
* Parse submit form in forum page.
* @param page
*/
private parseSubmitPageForm(page: Page): void {
const formElement = page.$('form#form');
const action = formElement.attr('action');
if (!action)
throw new Error('SIGAA: Forum submit page has form without action.');
const actionURL = new URL(action, page.url.href);
const postValues: Record<string, string> = {};
formElement
.find("input:not([type='button'])")
.each((index: number, element: cheerio.Element) => {
const name = page.$(element).attr('name');
if (name) postValues[name] = page.$(element).val();
});
this._submitTopicPageForm = {
action: actionURL,
postValues
};
}
/**
* Parse main page of forum.
* @param page
*/
private parseForumTable(page: Page): void {
const tableElement = page.$('table.formAva > tbody');
if (tableElement.length === 0)
throw new Error('SIGAA: Unexpected forum page without table element.');
const rows = tableElement.find('tr').toArray();
for (const row of rows) {
const headCellElement = page.$(row).find('th');
const dataCellElement = page.$(row).find('td');
const label = this.parser.removeTagsHtml(headCellElement.html());
const content = this.parser.removeTagsHtml(dataCellElement.html());
switch (label) {
case 'Título:': {
this._title = content;
break;
}
case 'Descrição:': {
this._description = content;
break;
}
case 'Autor(a):': {
this._author = content;
break;
}
case 'Arquivo:': {
const linkElement = page.$(dataCellElement).find('a');
if (linkElement.length === 1) {
const title = this.parser.removeTagsHtml(linkElement.html());
const onClick = linkElement.attr('onclick');
if (!onClick)
throw new Error('SIGAA: Invalid file format at forum page.');
const form = page.parseJSFCLJS(onClick);
const fileObj: FileData = {
title,
description: '',
form,
id: form.postValues.id,
instanceIndentifier: form.postValues.id
};
if (this._file) {
this._file.update(fileObj);
} else {
this._file = this.courseResourcesFactory.createFileFromFileData(
fileObj,
this.http,
async () => {
await this.getForumPage();
}
);
}
} else {
this._file = undefined;
}
break;
}
case 'Monitorar Leitura:': {
if (content === 'SIM') {
this._flagMonitorReading = true;
} else {
this._flagMonitorReading = false;
}
break;
}
case 'Tipo:': {
this._forumType = content;
break;
}
case 'Ordenação Padrão:': {
//TODO
break;
}
case 'Criado em:': {
const dates = this.parser.parseDates(content, 1);
this._creationDate = dates[0];
break;
}
default: {
console.log('WARNING:forum label not recognized:' + label);
}
}
}
}
private async loadForumPage() {
if (!this._fullForumPromise) {
this._fullForumPromise = this.getForumPage();
this._fullForumPromise.finally(() => {
this._fullForumPromise = null;
});
}
return this._fullForumPromise;
}
get title(): string {
this.checkIfItWasClosed();
return this._title;
}
/**
* Like 'Uma única discussão simples'
*/
async getForumType(): Promise<string> {
this.checkIfItWasClosed();
if (this._forumType === undefined) {
await this.loadForumPage();
}
if (!this._forumType)
throw new Error('SIGAA: Forum type could not be loaded.');
return this._forumType;
}
async getDescription(): Promise<string> {
this.checkIfItWasClosed();
if (this._description === undefined) {
await this.loadForumPage();
}
if (!this._description)
throw new Error('SIGAA: Forum description could not be loaded.');
return this._description;
}
/**
* Post author
*/
async getAuthor(): Promise<string> {
this.checkIfItWasClosed();
if (this._author === undefined) {
await this.loadForumPage();
}
if (!this._author)
throw new Error('SIGAA: Forum author could not be loaded.');
return this._author;
}
/**
* If notifications are enabled
*/
async getFlagMonitorReading(): Promise<boolean> {
this.checkIfItWasClosed();
if (this._flagMonitorReading === undefined) {
await this.loadForumPage();
}
if (!this._flagMonitorReading)
throw new Error('SIGAA: Forum monitor reading flag could not be loaded.');
return this._flagMonitorReading;
}
/**
* creation date of the forum.
*/
async getCreationDate(): Promise<Date> {
this.checkIfItWasClosed();
if (this._creationDate === undefined) {
await this.loadForumPage();
}
if (!this._creationDate)
throw new Error('SIGAA: Forum creation date could not be loaded.');
return this._creationDate;
}
/**
* File attached to the forum.
*/
async getFile(): Promise<File | undefined> {
this.checkIfItWasClosed();
if (this._file === undefined) {
await this.loadForumPage();
}
return this._file;
}
/**
* Number of topics
*/
async getNumOfTopics(): Promise<number> {
this.checkIfItWasClosed();
if (this._numOfTopics === undefined) {
await this.updateInstance();
}
if (!this._numOfTopics)
throw new Error('SIGAA: Forum number of topics could not be loaded.');
return this._numOfTopics;
}
get id(): string {
this.checkIfItWasClosed();
return this._id;
}
/**
* Post topic in forum
* @param title title of topic
* @param body body of topic
* @param file buffer of file attachment
* @param notify if notify members
*/
async postTopic(
title: string,
body: string,
file: string,
notify: boolean
): Promise<void> {
if (!title) {
throw new Error('SIGAA: Title topic forum cannot be empty.');
}
if (!body) {
throw new Error('SIGAA: Title body forum cannot be empty.');
}
if (!this._submitTopicPageForm) {
await this.loadForumPage();
}
if (!this._submitTopicPageForm)
throw new Error('SIGAA: Could not get the forum form.');
const page = await this.http.post(
this._submitTopicPageForm.action.href,
this._submitTopicPageForm.postValues
);
const formElement = page.$('form#form');
const action = formElement.attr('action');
if (!action)
throw new Error('SIGAA: Forum post page has form without action.');
const actionURl = new URL(action, page.url.href);
const inputHiddens = formElement
.find('form#form input[type="hidden"]')
.toArray();
const fileInput = formElement.find('input[type="file"]');
const submitButton = formElement.find('input[name="form:btnSalvar"]');
const notifyCheckbox = formElement.find('input[type="checkbox"]');
if (
inputHiddens.length === 0 ||
submitButton.length !== 1 ||
notifyCheckbox.length !== 1 ||
fileInput.length !== 1
)
throw new Error(
'SIGAA: Forum post page format is different than expected.'
);
const formData = new FormData();
for (const input of inputHiddens) {
const name = page.$(input).attr('name');
if (name) formData.set(name, page.$(input).val());
}
if (file) {
const name = fileInput.attr('name');
if (!name)
throw new Error('SIGAA: Forum post page has input file without name.');
formData.set(name, file);
}
if (notify) {
const name = notifyCheckbox.attr('name');
if (!name)
throw new Error(
'SIGAA: Forum post page has notify checkbox without name.'
);
formData.set(name, 'on');
}
formData.set('form:assunto', title);
formData.set('form:mensagem', body);
const sumbitName = page.$(submitButton).attr('name');
if (!sumbitName)
throw new Error('SIGAA: Forum post page has submit button without name.');
formData.set(sumbitName, page.$(submitButton).val());
const responsePage = await this.http.postMultipart(
actionURl.href,
formData
);
if (!responsePage.bodyDecoded.includes('Operação realizada com sucesso!')) {
throw new Error('SIGAA: Unexpected response forum post page.');
}
}
*getTopics(): Generator<Promise<boolean>, void, void> {
let stillHaveTopics = true;
while (stillHaveTopics) {
yield (async (): Promise<boolean> => {
stillHaveTopics = false;
return true;
})();
}
}
}