Skip to content

Commit 1267916

Browse files
committed
Implemented session ping (#13)
1 parent 9e06841 commit 1267916

File tree

6 files changed

+134
-3
lines changed

6 files changed

+134
-3
lines changed

README.md

+22
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,8 @@ const edupage = new Edupage();
7373
const lessons = timetable.lessons;
7474

7575
console.log(lessons);
76+
77+
edupage.exit(); //To exit the process
7678
})();
7779
```
7880

@@ -98,6 +100,8 @@ const edupage = new Edupage();
98100
const homeworks = lessons.reduce((arr, lesson) => (arr.push(...lesson.assignments), arr), []);
99101

100102
console.log(homeworks);
103+
104+
edupage.exit(); //To exit the process
101105
})();
102106
```
103107

@@ -122,6 +126,8 @@ const edupage = new Edupage();
122126
const timetables = await edupage.fetchTimetablesForDates(from, to);
123127

124128
console.log(timetables);
129+
130+
edupage.exit(); //To exit the process
125131
})();
126132
```
127133

@@ -154,6 +160,8 @@ const edupage = new Edupage();
154160

155161
console.log(success);
156162
}
163+
164+
edupage.exit(); //To exit the process
157165
})();
158166
```
159167

@@ -178,6 +186,8 @@ const edupage = new Edupage();
178186

179187
//Send the message
180188
await classmate.sendMessage(options);
189+
190+
edupage.exit(); //To exit the process
181191
})();
182192
```
183193

@@ -205,6 +215,8 @@ const edupage = new Edupage();
205215

206216
//Send the message
207217
await teacher.sendMessage(options);
218+
219+
edupage.exit(); //To exit the process
208220
})();
209221
```
210222

@@ -226,6 +238,8 @@ const edupage = new Edupage();
226238
const {materialData, resultsData} = await assignment.getData();
227239

228240
console.log(materialData, resultsData);
241+
242+
edupage.exit(); //To exit the process
229243
})();
230244
```
231245

@@ -254,6 +268,8 @@ const edupage = new Edupage();
254268

255269
//Console.log the result (🚨 This might not be precise!)
256270
console.log(success);
271+
272+
edupage.exit(); //To exit the process
257273
})();
258274
```
259275

@@ -322,6 +338,7 @@ class ASC extends RawData {
322338

323339
server: string;
324340
gsecHash: string;
341+
gpids: string[];
325342
gpid?: string;
326343
}
327344
```
@@ -510,6 +527,11 @@ class Edupage extends RawData {
510527
async uploadAttachment(filepath: string): Promise<Attachment>;
511528
async api(options: APIOptions): Promise<RawDataObject | string>;
512529

530+
scheduleSessionPing(): void;
531+
async pingSession(): Promise<boolean>;
532+
533+
exit(): void; // Stops internal timers to prevent process from hanging infinitely.
534+
513535
static compareDay(
514536
date1: Date | number | string,
515537
date2: Date | number | string

package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "edupage-api",
3-
"version": "0.7.14",
3+
"version": "0.8.0",
44
"description": "Simple node.js package to manage your EduPage account.",
55
"main": "index.js",
66
"scripts": {

src/ASC.js

+5
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,11 @@ class ASC extends RawData {
8181
*/
8282
this.gpid = null;
8383

84+
/**
85+
* @type {string[]}
86+
*/
87+
this.gpids = [];
88+
8489
/**
8590
* @type {number}
8691
*/

src/Edupage.js

+99-1
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ const Teacher = require("./Teacher");
88
const User = require("./User");
99
const {btoa, iterate} = require("../lib/utils");
1010
const {ENDPOINT, API_STATUS, TIMELINE_ITEM_TYPE} = require("./enums");
11+
const {SESSION_PING_INTERVAL_MS} = require("./constants");
1112
const Class = require("./Class");
1213
const Classroom = require("./Classroom");
1314
const Parent = require("./Parent");
@@ -147,6 +148,12 @@ class Edupage extends RawData {
147148
* @type {string}
148149
*/
149150
this.baseUrl = null;
151+
152+
//Used internally to keep track of Timeout object for session pinging
153+
Object.defineProperty(this, "_sessionPingTimeout", {
154+
enumerable: false,
155+
writable: true
156+
});
150157
}
151158

152159
/**
@@ -168,6 +175,8 @@ class Edupage extends RawData {
168175
//Update edupage data
169176
await this.refresh().catch(reject);
170177

178+
this.scheduleSessionPing();
179+
171180
resolve(this.user);
172181
}).catch(reject);
173182
});
@@ -440,7 +449,10 @@ class Edupage extends RawData {
440449
const _html = await this.api({url: ENDPOINT.DASHBOARD_GET_CLASSBOOK, method: "GET", type: "text"});
441450
const ids = [..._html.matchAll(/gpid="?(\d+)"?/gi)].map(e => e[1]);
442451

443-
if(ids.length) this.ASC.gpid = ids[ids.length - 1];
452+
if(ids.length) {
453+
this.ASC.gpids = ids;
454+
this.ASC.gpid = ids[ids.length - 1];
455+
}
444456
else throw new Error("Cannot find gpid value");
445457
} catch(err) {
446458
debug(`[Timetable] Could not get 'gpid' property`, err);
@@ -631,6 +643,91 @@ class Edupage extends RawData {
631643
});
632644
}
633645

646+
/**
647+
* Sends a session ping request
648+
* @returns {Promise<boolean>} Whether the ping was successful
649+
*/
650+
async pingSession() {
651+
debug(`[Login] Sening a session ping request...`);
652+
653+
const gpids = this.ASC.gpids;
654+
const success = await this.api({
655+
url: ENDPOINT.SESSION_PING,
656+
method: "POST",
657+
type: "text",
658+
data: {
659+
gpids: gpids.join(";")
660+
}
661+
}).then(data => {
662+
if(data == "notlogged") return false;
663+
else if(data == "OK") return true;
664+
665+
try {
666+
const obj = JSON.parse(data);
667+
if(obj.status == "notlogged") return false;
668+
else return true;
669+
} catch(err) {
670+
FatalError.throw(new ParseError(`Failed to parse session ping response as JSON: ${err.message}`), {data, gpids});
671+
}
672+
}).catch(err => {
673+
FatalError.warn(new APIError(`Failed to ping session: ${err.message}`), {err, gpids});
674+
return null;
675+
});
676+
677+
this.scheduleSessionPing();
678+
679+
//Failed to ping session
680+
if(success === null) {
681+
error(`[Login] Failed to ping session`);
682+
return false;
683+
}
684+
685+
//Successfully pinged session
686+
if(success) {
687+
debug(`[Login] Successfully pinged session`);
688+
return true;
689+
}
690+
691+
//Session is not logged in
692+
if(!success) {
693+
warn(`[Login] Session is not logged in, trying to log in...`);
694+
const loggedIn = await this.user.login(this.user.credentials.username, this.user.credentials.password)
695+
.then(() => {
696+
debug(`[Login] Successfully logged in`);
697+
return true;
698+
})
699+
.catch(err => {
700+
error(`[Login] Failed to log in:`, err);
701+
return false;
702+
});
703+
704+
return loggedIn;
705+
}
706+
}
707+
708+
/**
709+
* Schedules a session ping request
710+
*/
711+
scheduleSessionPing() {
712+
if(this._sessionPingTimeout) {
713+
clearTimeout(this._sessionPingTimeout);
714+
this._sessionPingTimeout = null;
715+
}
716+
717+
this._sessionPingTimeout = setTimeout(() => this.pingSession(), SESSION_PING_INTERVAL_MS);
718+
debug(`[Login] Scheduled session ping in ${SESSION_PING_INTERVAL_MS}ms`);
719+
}
720+
721+
/**
722+
* Stops internal timers to prevent process from hanging infinitely.
723+
*/
724+
exit() {
725+
if(this._sessionPingTimeout) {
726+
clearTimeout(this._sessionPingTimeout);
727+
this._sessionPingTimeout = null;
728+
}
729+
}
730+
634731
/**
635732
*
636733
* @param {Date|number|string} date1
@@ -696,6 +793,7 @@ class Edupage extends RawData {
696793
if(endpoint == ENDPOINT.ELEARNING_TEST_RESULTS) url = `/elearning/?cmd=EtestCreator&akcia=getResultsData`;
697794
if(endpoint == ENDPOINT.ELEARNING_CARDS_DATA) url = `/elearning/?cmd=EtestCreator&akcia=getCardsData`;
698795
if(endpoint == ENDPOINT.GRADES_DATA) url = `/znamky/?barNoSkin=1`;
796+
if(endpoint == ENDPOINT.SESSION_PING) url = this._data?._edubar?.sessionPingUrl || `/login/eauth?portalping`;
699797

700798
if(!url) throw new TypeError(`Invalid API endpoint '${endpoint}'`);
701799
else return this.baseUrl + url;

src/constants.js

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
const SESSION_PING_INTERVAL_MS = 10 * 60 * 1000; //10 minutes
2+
3+
module.exports = {
4+
SESSION_PING_INTERVAL_MS,
5+
};

src/enums.js

+2-1
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,8 @@ const ENDPOINT = {
5454
ELEARNING_TEST_DATA: 13,
5555
ELEARNING_TEST_RESULTS: 14,
5656
ELEARNING_CARDS_DATA: 15,
57-
GRADES_DATA: 16
57+
GRADES_DATA: 16,
58+
SESSION_PING: 17
5859
};
5960

6061
/**

0 commit comments

Comments
 (0)