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-news-student.ts
executable file
·108 lines (98 loc) · 2.6 KB
/
sigaa-news-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
import { Parser } from '@helpers/sigaa-parser';
import { UpdatableResourceData } from '@resources/sigaa-resource-manager';
import {
AbstractUpdatableResource,
UpdatableResource,
UpdatableResourceCallback
} from '@resources/updatable-resource';
import { HTTP } from '@session/sigaa-http';
import { SigaaForm } from '@session/sigaa-page';
/**
* @category Internal
*/
export interface NewsData extends UpdatableResourceData {
title: string;
form: SigaaForm;
id: string;
}
/**
* @category Public
*/
export interface News extends UpdatableResource<NewsData> {
readonly title: string;
getContent(): Promise<string>;
getDate(): Promise<Date>;
}
/**
* @category Internal
*/
export class SigaaNews extends AbstractUpdatableResource implements News {
private _form!: SigaaForm;
private _title!: string;
private _content?: string;
private _date?: Date;
constructor(
private http: HTTP,
private parser: Parser,
options: NewsData,
updater: UpdatableResourceCallback
) {
super(options.instanceIndentifier, updater);
this.update(options);
}
update(newsOptions: NewsData): void {
this._title = newsOptions.title;
this._form = newsOptions.form;
this.isClosed = false;
}
get id(): string {
this.checkIfItWasClosed();
return this._form.postValues.id;
}
get title(): string {
this.checkIfItWasClosed();
return this._title;
}
async getContent(): Promise<string> {
this.checkIfItWasClosed();
if (this._content === undefined) {
await this.getFullNews();
}
return this._content as string;
}
async getDate(): Promise<Date> {
this.checkIfItWasClosed();
if (this._date === undefined) {
await this.getFullNews();
}
return this._date as Date;
}
private async getFullNews(retry = true): Promise<void> {
try {
const page = await this.http.post(
this._form.action.href,
this._form.postValues
);
if (page.statusCode !== 200) {
throw new Error('SIGAA: Invalid status code at news page.');
}
const newsElement = page.$('ul.form');
if (newsElement.length === 0) {
throw new Error('SIGAA: Invalid news page.');
}
const els = newsElement.find('span');
const dateString = this.parser.removeTagsHtml(els.eq(1).html());
this._date = this.parser.parseDates(dateString, 1)[0];
this._content = this.parser.removeTagsHtml(
newsElement.find('div').html()
);
} catch (err) {
if (retry) {
await this.updateInstance();
return this.getFullNews(false);
} else {
throw err;
}
}
}
}