This repository has been archived by the owner on Sep 1, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
313 lines (264 loc) · 11.1 KB
/
index.js
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
const puppeteer = require('puppeteer');
const fs = require('fs');
const esformatter = require('esformatter');
const readline = require('readline');
var Writable = require('stream').Writable;
var mutableStdout = new Writable({
write: function(chunk, encoding, callback) {
if (!this.muted)
process.stdout.write(chunk, encoding);
callback();
}
});
const filename = "data.json";
let USERNAME = "";
let PASSWORD = "";
const LINKS = {
home: "https://uozone2.uottawa.ca/",
beforeExtraction: "https://www.uocampus.uottawa.ca/psp/csprpr9www/EMPLOYEE/HRMS/c/SA_LEARNER_SERVICES.SSR_SSENRL_LIST.GBL?languageCd=ENG",
extraction: "https://www.uocampus.uottawa.ca/psc/csprpr9www/EMPLOYEE/HRMS/c/SA_LEARNER_SERVICES.SSR_SSENRL_LIST.GBL?languageCd=ENG"
}
let page;
let browser;
async function asyncMain() {
// Extracts information
console.log("----- EXTRACTING INFORMATION")
await page.goto(LINKS.extraction);
await preliminarySteps();
await navigateUozone();
}
async function preliminarySteps() {
await page.exposeFunction("navigateUozone", navigateUozone);
await page.exposeFunction("writeToConsole", message => {
console.log(message);
});
await page.exposeFunction("finished", async data => {
console.log("----- COURSE INFO");
console.log("----- SAVING THE DATA IN THE FILE NAMED: " + __dirname + "\\" + filename);
fs.writeFile(filename, esformatter.format(data), (err) => {
if (err) throw err;
});
console.log("----- LOGING OUT");
await page.goto(LINKS.home + "/user/logout");
browser.close();
console.log("----- BROWSER CLOSED")
});
await page.evaluate(() => {
let id = 0;
let numRadio = document.getElementsByClassName("PSRADIOBUTTON").length;
let element = document.getElementById('WAIT_win0');
function loading() {
var array = document.getElementById("WAIT_win0").getAttribute("style").split(/(:)*(;)|(;)*(:)/).filter(s => s !== undefined && s.trim() !== ":" && s.trim() !== ";" && s !== "").map(s => s.trim());
for (var i = 0; i < array.length - 1; i++) {
if (array[i] === "display" && array[i + 1] === "block" || array[i] === "visibility" && array[i + 1] === "visible") {
return true;
}
}
return false;
}
var observer = new MutationObserver(async (mutations) => {
await (async (mutation) => {
if (mutation.type == "attributes" && loading() === false) {
id++;
writeToConsole("----- EXTRACTING INFORMATION - STEP " + id + "/" + numRadio * 2);
if (id <= numRadio * 2) {
if (numRadio * 2 !== id) {
await navigateUozone();
}
if (id === numRadio * 2) {
finished(localStorage.getItem("currentInfo"));
}
}
}
})(mutations[0]);
});
observer.observe(element, {
attributes: true
});
});
}
async function navigateUozone() {
await page.evaluate(() => {
const LOCAL_TERM = "currentTerm";
const LOCAL_INFO = "currentInfo";
const LOCAL_NUM_BUTTON = "numRadioButton";
const weekdayConcordance = {
Mo: "Monday",
Tu: "Tuesday",
We: "Wednesday",
Th: "Thursday",
Fr: "Friday",
Sa: "Sathurday",
Su: "Sunday"
};
function extractCourseSchedule() {
let basicInfo = document.getElementById("DERIVED_REGFRM1_SSR_STDNTKEY_DESCR$11$").innerHTML.split(" | ");
let termInfo = basicInfo[0].split(" ");
let year = termInfo[0];
let trimester = termInfo[1];
let term = {
year,
trimester,
level: basicInfo[1],
courses: []
};
let tables = Array.from(document.getElementsByClassName("PSGROUPBOXWBO"));
tables = tables.filter(table => table.getElementsByTagName("input").length === 0);
for (var i = 0; i < tables.length; i++) {
let basicInfo = tables[i].getElementsByClassName("PAGROUPDIVIDER")[0].innerHTML.split("-");
let contentTable = tables[i].getElementsByClassName("PSLEVEL3GRIDNBO");
let firstRow = contentTable[0].getElementsByClassName("PSLEVEL3GRIDROW");
let secondRow = contentTable[1].getElementsByClassName("PSLEVEL3GRIDROW");
let classes = [];
for (var j = 0; j < secondRow.length / 7; j++) {
let date = getHTMLContent(secondRow[j * 7 + 6]);
if (date.split(" - ").length === 2) {
date = date.split(" - ").sort((a, b) => {
return new Date(a) - new Date(b);
});
}
let startDate = date[0];
let endDate = date[1];
let time = getHTMLContent(secondRow[j * 7 + 3]);
let weekday = weekdayConcordance[time.substr(0, 2)];
time = time.substr(3).split(" - ").sort((a, b) => {
return new Date('1970/01/01 ' + a) - new Date('1970/01/01 ' + b);
});
let startTime = time[0];
let endTime = time[1];
let place = getHTMLContent(secondRow[j * 7 + 4]).split(/[\(*\)]/).map(s => s.trim());
let address = place[0];
let building = place[1];
let room = place[2];
classes.push({
classNumber: getHTMLContent(secondRow[j * 7]),
section: getHTMLContent(secondRow[j * 7 + 1]),
type: getHTMLContent(secondRow[j * 7 + 2]),
instructor: getHTMLContent(secondRow[j * 7 + 5]),
startTime,
endTime,
startDate,
endDate,
weekday,
address,
building,
room
});
}
term.courses.push({
code: basicInfo[0].trim(),
name: basicInfo[1].trim(),
status: firstRow[0].textContent.trim(),
units: firstRow[1].textContent.trim(),
grading: firstRow[2].textContent.trim(),
grade: firstRow[3].textContent.trim(),
classes
});
}
return term;
}
function getHTMLContent(content) {
return content.textContent.trim();
}
function extractInfo() {
let term = extractCourseSchedule();
let data = [];
if (localStorage.getItem(LOCAL_INFO) === null) {
data = [term];
} else {
data = [...JSON.parse(localStorage.getItem(LOCAL_INFO)), term];
}
localStorage.setItem(LOCAL_INFO, JSON.stringify(data));
}
function navigateUozonePage() {
if (localStorage.getItem(LOCAL_NUM_BUTTON) === null) {
localStorage.setItem(LOCAL_NUM_BUTTON, document.getElementsByClassName("PSRADIOBUTTON").length);
}
if (document.getElementsByClassName("PSRADIOBUTTON").length === parseInt(localStorage.getItem(LOCAL_NUM_BUTTON))) {
if (localStorage.getItem(LOCAL_TERM) === null) {
localStorage.setItem(LOCAL_TERM, 0);
} else {
localStorage.setItem(LOCAL_TERM, parseInt(localStorage.getItem(LOCAL_TERM)) + 1);
}
document.getElementsByClassName("PSRADIOBUTTON")[localStorage.getItem(LOCAL_TERM)].checked = true;
document.getElementById("DERIVED_SSS_SCT_SSR_PB_GO").click();
} else {
extractInfo();
document.getElementById("DERIVED_SSS_SCT_SSS_TERM_LINK").click();
}
}
if (localStorage.getItem(LOCAL_NUM_BUTTON) === null || localStorage.getItem(LOCAL_TERM) === null || parseInt(localStorage.getItem(LOCAL_TERM)) !== parseInt(localStorage.getItem(LOCAL_NUM_BUTTON))) {
window.onload = navigateUozonePage();
}
});
}
async function uozoneLogIn() {
await page.evaluate((username, password) => {
document.getElementById('userNameInput').value = username;
document.getElementById('passwordInput').value = password;
document.forms['loginForm'].submit();
}, USERNAME, PASSWORD);
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
function getCredentials() {
const rl = readline.createInterface({
input: process.stdin,
output: mutableStdout,
terminal: true
});
rl.question('Enter your uoZone\'s username > ', (answer) => {
USERNAME = answer;
process.stdout.write('Enter you uoZone\'s password > ');
mutableStdout.muted = true;
rl.question('', (answer) => {
PASSWORD = answer;
mutableStdout.muted = false;
rl.close();
process.stdout.write('\033c');
verifyCredentials();
});
});
}
async function verifyCredentials() {
// Goes to uoZone's website
await page.goto(LINKS.home);
// Logs in to uoZone --- Potential issue: to go to the next step, its time based
await uozoneLogIn();
await sleep(2000);
// Goes to the website with the course information to see if you succesfully loged in
await page.goto(LINKS.beforeExtraction);
// Checks if the page's title is equal to "my class schedule" to know if the user has successfully loged in
if (await page.evaluate(() => {return document.title.toLowerCase().trim()}) === "my class schedule") {
console.log("Your credentials are valid\n");
asyncMain()
} else {
console.log("Your credentials are not valid");
getCredentials();
}
}
async function broswerSetup() {
// Opens a browser in the background and opens a new tab
browser = await puppeteer.launch({ headless: true });
page = await browser.newPage();
// Does not load images on the webpage (speeds up load times)
await page.setRequestInterception(true);
await page.on('request', request => {
if (request.resourceType() === 'image')
request.abort();
else
request.continue();
});
// Prints everything from the broswer console in the terminal and removes the errors from not loading images
await page.on('console', msg => {
if (msg.text().trim() !== "Failed to load resource: net::ERR_FAILED") {
console.log('PAGE LOG:', msg.text())
}
});
}
async function main() {
await broswerSetup();
getCredentials();
}
main();