-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbcm.js
More file actions
301 lines (264 loc) · 13.3 KB
/
bcm.js
File metadata and controls
301 lines (264 loc) · 13.3 KB
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
import axios from 'axios';
import chalk from 'chalk';
import readline from "readline";
import fs from 'fs';
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
// STARTUP SPLASH
console.log(
chalk.red(`
______ _____ ___ ___
| ___ \\ / __ \\ | \\/ |
| |_/ /_ __ _____ ___ __ | / \\/ ___ _ _ _ __ ___ ___ | . . | __ _ _ __ __ _ __ _ ___ _ __
| ___ \\ '__/ _ \\ \\ /\\ / / '_ \\ | | / _ \\| | | | '__/ __|/ _ \\ | |\\/| |/ _\` | '_ \\ / _\` |/ _\` |/ _ \\ '__|
| |_/ / | | (_) \\ V V /| | | | | \\__/\\ (_) | |_| | | \\__ \\ __/ | | | | (_| | | | | (_| | (_| | __/ |
\\____/|_| \\___/ \\_/\\_/ |_| |_| \\____/\\___/ \\__,_|_| |___/\\___| \\_| |_/\\__,_|_| |_|\\__,_|\\__, |\\___|_|
__/ | \n `)
+ chalk.bgRed("By: Milo (@onemilon)") + chalk.red(` |___/ \n`)
);
// HELPERS
// ---------------------------------------------------------------------------------------------------
function parseSemID(input) {
if(!isNaN(input)) return input; // input is already a semester ID
let failed = false;
let labelInfo = input.split(" ");
let mod;
if(labelInfo[0] == "Summer") mod = 0;
else if(labelInfo[0] == "Fall") mod = 10;
else if(labelInfo[0] == "Winter") mod = -85;
else if(labelInfo[0] == "Spring") mod = -80;
else {
failed = true;
console.log("Oops! Your input did not contain any semester keywords. Please try again.");
userInput();
}
if(!failed) {
console.log(`Your ${chalk.cyan("semester ID")} should be ${chalk.cyan(202000 + ((parseInt(labelInfo[1]) - 2020) * 100) + mod)}\n`);
return (202000 + ((parseInt(labelInfo[1]) - 2020) * 100) + mod).toString();
}
}
function displayHelp() {
console.log(
chalk.dim("———————————————————————————————————————————————————————————\n") +
"Commands available:\n" +
"Help — Display this message\n" +
chalk.italic("1 — Add Course to Favorites\n") +
chalk.italic("2 — Add Courses from File to Favorites\n") +
chalk.italic("3 — Remove Course from Favorites\n") +
chalk.italic("4 — Clear all Courses from Favorites\n") +
chalk.italic("5 — Check Favorites Availability in Semester\n") +
chalk.italic("6 — List Favorite Courses\n") +
chalk.dim("———————————————————————————————————————————————————————————\n")
);
}
// TODO: improve using courses sample
function addCourseToFavorites(data, courseInput) {
fs.readFile('favorites.json', function (jsonErr, jsonData) {
let json = JSON.parse(jsonData)
if(courseInput.includes(" ")) { // Based on code
let words = courseInput.split(" ");
let match = data["results"].find((course) => course["code"] == words[0] + " " + words[1]);
if(match) {
json["courses"].push(match);
fs.writeFileSync("favorites.json", JSON.stringify(json));
console.log("Added!\n");
userInput();
} else {
console.log("No match found for course code! Please try again.\n");
userInput();
}
} else if(!isNaN(courseInput)) { // Based on CRN
let match = data["results"].find((course) => course["crn"] == courseInput);
if(match) {
json["courses"].push(match);
fs.writeFileSync("favorites.json", JSON.stringify(json));
console.log("Added!\n");
userInput();
} else {
console.log("No match found for course CRN! Please try again.\n");
userInput();
}
} else {
console.log("Course format not recognized!\n");
userInput();
}
});
}
function addCoursesToFavorites(data, pathInput) {
fs.readFile('favorites.json', async function (jsonErr, jsonData) {
let json = JSON.parse(jsonData);
let lines = 0;
const courseStream = readline.createInterface({
input: fs.createReadStream(pathInput)
});
courseStream.on('line', function(courseInput) {
if(courseInput.includes(" ")) { // Based on code
let words = courseInput.split(" ");
let match = data["results"].find((course) => course["code"] == words[0] + " " + words[1]);
if(match) {
lines++;
json["courses"].push(match);
}
} else if(!isNaN(courseInput)) { // Based on CRN
let match = data["results"].find((course) => course["crn"] == courseInput);
if(match) {
lines++;
json["courses"].push(match);
}
} else {
console.log("Course format not recognized!\n");
userInput();
}
});
courseStream.on('close', () => {
fs.writeFileSync("favorites.json", JSON.stringify(json));
console.log(`${lines} courses saved!\n`);
userInput();
})
});
}
function removeCourseFromFavorites(courseInput) {
fs.readFile('favorites.json', async function (jsonErr, jsonData) {
let json = JSON.parse(jsonData);
if(courseInput.includes(" ")) { // Based on code
let words = courseInput.split(" ");
let filteredList = json["courses"].filter((course) => course["code"] != words[0] + " " + words[1]);
let filteredJson = { courses: filteredList };
if(filteredJson["courses"].length == json["courses"].length) console.log(`Unable to find ${chalk.green("course code")} in favorites. Please try again.\n`);
else {
fs.writeFileSync("favorites.json", JSON.stringify(filteredJson));
console.log("Course removed successfully!\n");
}
} else if(!isNaN(courseInput)) { // Based on CRN
let filteredList = json["courses"].filter((course) => course["crn"] != courseInput);
let filteredJson = { courses: filteredList };
if(filteredJson["courses"].length == json["courses"].length) console.log(`Unable to find ${chalk.yellow("CRN")} in favorites. Please try again.\n`);
else {
fs.writeFileSync("favorites.json", JSON.stringify(filteredJson));
console.log("Course removed successfully!\n");
}
} else {
console.log("Course format not recognized!\n");
}
userInput();
});
}
function printFavorites() {
fs.readFile('favorites.json', async function (jsonErr, jsonData) {
let json = JSON.parse(jsonData);
console.log("Favorite courses:")
for(const course in json["courses"]) {
console.log(`☆ ${chalk.yellow("[" + json['courses'][course]['crn'] + "]")} ${json["courses"][course]["code"]} (${json["courses"][course]["title"]})`)
}
console.log();
userInput();
});
}
// COMMANDS
// ---------------------------------------------------------------------------------------------------
function userInput() {
rl.question(`Enter a command or ${chalk.red("\"exit\"")} to end program: `, function(command) {
command = command.toLowerCase();
if(command == "exit") {
rl.close();
} else {
if(command == "help") {
displayHelp();
userInput();
}
// Add courses to favorites
else if(command == "1" || command == "2") {
rl.question(`Enter ${chalk.cyan("semester ID")} or label: `, (semesterInput)=>{
let semID = parseSemID(semesterInput);
const dataPayload = {
other: {srcdb: semID},
criteria: [{field:"is_ind_study",value:"N"},{field:"is_canc",value:"N"}]
}
axios.post("https://cab.brown.edu/api/?page=fose&route=search&is_ind_study=N&is_canc=N", dataPayload)
.then(({data}) => {
if(data["fatal"]) {
console.log(`Error encountered requesting Brown's course list (is your semester correct?): "${data["fatal"]}"`);
userInput();
}
else if(command == "1") {
rl.question(`Enter ${chalk.yellow("course CRN")} or ${chalk.green("course code")}: `, (courseInput)=>{
addCourseToFavorites(data, courseInput, true);
})
} else {
rl.question(`Enter ${chalk.yellow("path to file with line-separated courses")}: `, async (pathInput)=>{
addCoursesToFavorites(data, pathInput);
})
}
})
.catch((err) => {
console.log(`Error encountered requesting Brown's course list (is your semester correct?): ${err}`);
userInput();
});
});
// Remove courses from favorites
} else if(command == "3") {
rl.question(`Enter ${chalk.yellow("course CRN")} or ${chalk.green("course code")}: `, (courseInput)=>{
removeCourseFromFavorites(courseInput);
});
// Clear favorites list
} else if(command == "4") {
fs.writeFileSync("favorites.json", "{\"courses\": []}");
console.log("All courses removed!\n");
userInput();
// Check favorites availability
} else if(command == "5") {
rl.question(`Enter ${chalk.cyan("semester ID")} or label: `, (semesterInput)=>{
let semID = parseSemID(semesterInput);
const dataPayload = {
other: {srcdb: semID},
criteria: [{field:"is_ind_study",value:"N"},{field:"is_canc",value:"N"}]
}
axios.post("https://cab.brown.edu/api/?page=fose&route=search&is_ind_study=N&is_canc=N", dataPayload)
.then(({data}) => {
if(data["fatal"]) {
console.log(`Error encountered requesting Brown's course list (is your semester correct?): "${data["fatal"]}"`);
userInput();
return;
}
fs.readFile('favorites.json', async function (jsonErr, jsonData) {
let json = JSON.parse(jsonData);
let coursesFound = [];
let coursesMissed = [];
for(const course in json["courses"]) {
let result = data["results"].find((item) => item["crn"] == json["courses"][course]["crn"]);
if(result) coursesFound.push(json["courses"][course]);
else coursesMissed.push(json["courses"][course]);
}
console.log(`${chalk.green("Courses repeated:")}`);
for(let courseFound in coursesFound) {
console.log(`+ ${chalk.green(coursesFound[courseFound]["code"])} (${coursesFound[courseFound]["title"]})`);
}
console.log(`\n\n${chalk.red("Courses not found:")}`);
for(let courseMissed in coursesMissed) {
console.log(`- ${chalk.red(coursesMissed[courseMissed]["code"])} (${coursesMissed[courseMissed]["title"]})`);
}
console.log("\n");
userInput();
});
})
.catch((err) => {
console.log(`Error encountered requesting Brown's course list (is your semester correct?): ${err}`);
userInput();
})
});
// Print user favorites
} else if(command == "6") {
printFavorites();
}
//...
else {
console.log(`Command not recognized. Please try again, or use "help" to display help message`);
userInput();
}
}
})
}
displayHelp();
userInput();