Skip to content

Commit

Permalink
Implemented session ping (#13)
Browse files Browse the repository at this point in the history
  • Loading branch information
loumadev committed Jan 23, 2022
1 parent 9e06841 commit 1267916
Show file tree
Hide file tree
Showing 6 changed files with 134 additions and 3 deletions.
22 changes: 22 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,8 @@ const edupage = new Edupage();
const lessons = timetable.lessons;

console.log(lessons);

edupage.exit(); //To exit the process
})();
```

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

console.log(homeworks);

edupage.exit(); //To exit the process
})();
```

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

console.log(timetables);

edupage.exit(); //To exit the process
})();
```

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

console.log(success);
}

edupage.exit(); //To exit the process
})();
```

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

//Send the message
await classmate.sendMessage(options);

edupage.exit(); //To exit the process
})();
```

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

//Send the message
await teacher.sendMessage(options);

edupage.exit(); //To exit the process
})();
```

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

console.log(materialData, resultsData);

edupage.exit(); //To exit the process
})();
```

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

//Console.log the result (🚨 This might not be precise!)
console.log(success);

edupage.exit(); //To exit the process
})();
```

Expand Down Expand Up @@ -322,6 +338,7 @@ class ASC extends RawData {

server: string;
gsecHash: string;
gpids: string[];
gpid?: string;
}
```
Expand Down Expand Up @@ -510,6 +527,11 @@ class Edupage extends RawData {
async uploadAttachment(filepath: string): Promise<Attachment>;
async api(options: APIOptions): Promise<RawDataObject | string>;

scheduleSessionPing(): void;
async pingSession(): Promise<boolean>;

exit(): void; // Stops internal timers to prevent process from hanging infinitely.

static compareDay(
date1: Date | number | string,
date2: Date | number | string
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "edupage-api",
"version": "0.7.14",
"version": "0.8.0",
"description": "Simple node.js package to manage your EduPage account.",
"main": "index.js",
"scripts": {
Expand Down
5 changes: 5 additions & 0 deletions src/ASC.js
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,11 @@ class ASC extends RawData {
*/
this.gpid = null;

/**
* @type {string[]}
*/
this.gpids = [];

/**
* @type {number}
*/
Expand Down
100 changes: 99 additions & 1 deletion src/Edupage.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ const Teacher = require("./Teacher");
const User = require("./User");
const {btoa, iterate} = require("../lib/utils");
const {ENDPOINT, API_STATUS, TIMELINE_ITEM_TYPE} = require("./enums");
const {SESSION_PING_INTERVAL_MS} = require("./constants");
const Class = require("./Class");
const Classroom = require("./Classroom");
const Parent = require("./Parent");
Expand Down Expand Up @@ -147,6 +148,12 @@ class Edupage extends RawData {
* @type {string}
*/
this.baseUrl = null;

//Used internally to keep track of Timeout object for session pinging
Object.defineProperty(this, "_sessionPingTimeout", {
enumerable: false,
writable: true
});
}

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

this.scheduleSessionPing();

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

if(ids.length) this.ASC.gpid = ids[ids.length - 1];
if(ids.length) {
this.ASC.gpids = ids;
this.ASC.gpid = ids[ids.length - 1];
}
else throw new Error("Cannot find gpid value");
} catch(err) {
debug(`[Timetable] Could not get 'gpid' property`, err);
Expand Down Expand Up @@ -631,6 +643,91 @@ class Edupage extends RawData {
});
}

/**
* Sends a session ping request
* @returns {Promise<boolean>} Whether the ping was successful
*/
async pingSession() {
debug(`[Login] Sening a session ping request...`);

const gpids = this.ASC.gpids;
const success = await this.api({
url: ENDPOINT.SESSION_PING,
method: "POST",
type: "text",
data: {
gpids: gpids.join(";")
}
}).then(data => {
if(data == "notlogged") return false;
else if(data == "OK") return true;

try {
const obj = JSON.parse(data);
if(obj.status == "notlogged") return false;
else return true;
} catch(err) {
FatalError.throw(new ParseError(`Failed to parse session ping response as JSON: ${err.message}`), {data, gpids});
}
}).catch(err => {
FatalError.warn(new APIError(`Failed to ping session: ${err.message}`), {err, gpids});
return null;
});

this.scheduleSessionPing();

//Failed to ping session
if(success === null) {
error(`[Login] Failed to ping session`);
return false;
}

//Successfully pinged session
if(success) {
debug(`[Login] Successfully pinged session`);
return true;
}

//Session is not logged in
if(!success) {
warn(`[Login] Session is not logged in, trying to log in...`);
const loggedIn = await this.user.login(this.user.credentials.username, this.user.credentials.password)
.then(() => {
debug(`[Login] Successfully logged in`);
return true;
})
.catch(err => {
error(`[Login] Failed to log in:`, err);
return false;
});

return loggedIn;
}
}

/**
* Schedules a session ping request
*/
scheduleSessionPing() {
if(this._sessionPingTimeout) {
clearTimeout(this._sessionPingTimeout);
this._sessionPingTimeout = null;
}

this._sessionPingTimeout = setTimeout(() => this.pingSession(), SESSION_PING_INTERVAL_MS);
debug(`[Login] Scheduled session ping in ${SESSION_PING_INTERVAL_MS}ms`);
}

/**
* Stops internal timers to prevent process from hanging infinitely.
*/
exit() {
if(this._sessionPingTimeout) {
clearTimeout(this._sessionPingTimeout);
this._sessionPingTimeout = null;
}
}

/**
*
* @param {Date|number|string} date1
Expand Down Expand Up @@ -696,6 +793,7 @@ class Edupage extends RawData {
if(endpoint == ENDPOINT.ELEARNING_TEST_RESULTS) url = `/elearning/?cmd=EtestCreator&akcia=getResultsData`;
if(endpoint == ENDPOINT.ELEARNING_CARDS_DATA) url = `/elearning/?cmd=EtestCreator&akcia=getCardsData`;
if(endpoint == ENDPOINT.GRADES_DATA) url = `/znamky/?barNoSkin=1`;
if(endpoint == ENDPOINT.SESSION_PING) url = this._data?._edubar?.sessionPingUrl || `/login/eauth?portalping`;

if(!url) throw new TypeError(`Invalid API endpoint '${endpoint}'`);
else return this.baseUrl + url;
Expand Down
5 changes: 5 additions & 0 deletions src/constants.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
const SESSION_PING_INTERVAL_MS = 10 * 60 * 1000; //10 minutes

module.exports = {
SESSION_PING_INTERVAL_MS,
};
3 changes: 2 additions & 1 deletion src/enums.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,8 @@ const ENDPOINT = {
ELEARNING_TEST_DATA: 13,
ELEARNING_TEST_RESULTS: 14,
ELEARNING_CARDS_DATA: 15,
GRADES_DATA: 16
GRADES_DATA: 16,
SESSION_PING: 17
};

/**
Expand Down

0 comments on commit 1267916

Please sign in to comment.