-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
477 lines (401 loc) · 14.5 KB
/
Copy pathindex.js
File metadata and controls
477 lines (401 loc) · 14.5 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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
const express = require('express');
const mongoose = require('mongoose');
const path = require('path');
const methodOverride = require('method-override');
const ejs_mate = require('ejs-mate');
const catchAsync = require('./utils/catchAsync');
const ExpressError = require('./utils/ExpressError');
const session = require('express-session');
const passport = require('passport');
const LocalStrategy = require('passport-local');
const MongoDBStore = require('connect-mongo');
const User = require('./models/user');
const Unit = require('./models/unit');
const Module = require('./models/module');
const app = express();
// CONFIG:
const dbUrl = process.env.DB_URL || "mongodb://localhost:27017/stash-db"
//Connecting to database:
mongoose.connect(dbUrl, {
useNewUrlParser: true,
useUnifiedTopology: true
});
const db = mongoose.connection;
db.on("error", console.error.bind(console, "conection error:"));
db.once("open", () => {
console.log("Database connected");
});
//Setting app engine to ejs mate:
app.engine('ejs', ejs_mate);
//Setting app to reference view folder:
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
//Ask express to help decode our req bodies:
app.use(express.urlencoded({ extended: true }));
//Allow us to override method types (can use PUT etc.):
app.use(methodOverride('_method'));
//Public folder:
app.use(express.static(__dirname + "/public/"));
//Configuring Session:
const secret = process.env.SECRET || 'thisshouldbeabettersecret!'
const store = MongoDBStore.create({
mongoUrl: dbUrl,
touchAfter: 24 * 60 * 60,
crypto: {
secret: secret
}
});
store.on("error", function (e) {
console.log("SESSION STORE ERROR", e);
})
const sessionConfig = {
store: store,
secret: secret,
resave: false,
saveUninitialized: true
}
app.use(session(sessionConfig));
//Passport:
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
//Locals:
app.use(async (req, res, next) => {
// Allows all templates access to user:
res.locals.user = req.user;
next();
})
//Middleware for checking login:
const validateIsLoggedIn = (req, res, next) => {
if (!req.isAuthenticated()) {
return res.redirect('/login');
}
next();
}
//LANDING PAGE:
app.get('/', (req, res) => {
res.render('home');
})
//TIMETABLE:
function sortUnitsByTimings(objects) {
return objects.sort((a, b) => {
const timingA = a.timings.timingStart;
const timingB = b.timings.timingStart;
// Compare the timing start values
if (timingA < timingB) {
return -1;
} else if (timingA > timingB) {
return 1;
} else {
return 0;
}
});
}
//GET Index page with parameters
app.get('/timetable/:weekOrMonth/:period', validateIsLoggedIn, catchAsync(async (req, res) => {
const weekOrMonth = req.params.weekOrMonth;
const period = req.params.period;
let formattedPeriod = period;
if (weekOrMonth == "week" && period == "today") {
const today = new Date();
const dayOfWeek = today.getDay();
const diff = today.getDate() - dayOfWeek + (dayOfWeek === 0 ? -6 : 1);
const monday = new Date(today.setDate(diff));
const sunday = new Date(monday);
sunday.setDate(monday.getDate() + 6);
const options = { month: 'long', day: 'numeric', year: 'numeric' };
const formattedMonday = monday.toLocaleDateString('en', options).replace(/\//g, '.');
const formattedSunday = sunday.toLocaleDateString('en', options).replace(/\//g, '.');
formattedPeriod = formattedMonday + " - " + formattedSunday;
} else if (weekOrMonth == "month" && period == "today") {
const today = new Date();
const month = today.toLocaleString('default', { month: 'long' });
const monthString = month.charAt(0).toUpperCase() + month.slice(1);
const currentYear = new Date().getFullYear();
formattedPeriod = monthString + " " + currentYear;
}
var modules = await Module.find({userId: req.user.id});
var units = [];
for (let module of modules) {
var moduleUnits = await Unit.find({moduleId: module._id.toString()});
for (let moduleUnit of moduleUnits) {
units.push(moduleUnit);
}
}
units = sortUnitsByTimings(units);
res.render('timetable/index', { units, unitsString: JSON.stringify(units), weekOrMonth, formattedPeriod });
}))
//DELETE lesson
app.delete('/timetable/:id', validateIsLoggedIn, catchAsync(async (req, res) => {
const { id } = req.params;
await Unit.findByIdAndDelete(id);
res.redirect('/timetable/week/today');
}))
//WEEKLY TASK:
const hillclimb = require('./hillclimbing.js').hillclimb;
//POST make new weekly task
app.post('/weekly-tasks', validateIsLoggedIn, catchAsync(async (req, res) => {
// Create new weekly task unit:
var newWeeklyTaskBody = req.body;
newWeeklyTaskBody.userId = req.user.id;
newWeeklyTaskBody.type = "WeeklyTask";
newWeeklyTaskBody.colour = "#696969";
newWeeklyTaskBody.isAssigned = false;
const newWeeklyTask = new Unit(newWeeklyTaskBody);
await newWeeklyTask.save();
// Assign task:
const assignedUnits = await Unit.find({userId: req.user.id, isAssigned: true});
const optimalSchedule = hillclimb(assignedUnits, newWeeklyTask.toObject());
// Not enough timeslots to finish before deadline
if (optimalSchedule <= 0) {
res.sendStatus(401);
return;
}
for (let unit of optimalSchedule) {
if (!unit.isAssigned) {
unit.isAssigned = true;
await Unit.findByIdAndUpdate(unit._id, unit);
}
}
res.sendStatus(200);
}))
//Helper function to calculate time between:
function calculateTimeDifference(timingStart, timingEnd) {
const startTime = parseInt(timingStart);
const endTime = parseInt(timingEnd);
const diffHours = Math.abs(endTime - startTime) / 100;
return diffHours;
}
//PUT edit weekly task
app.put('/weekly-tasks/:id', validateIsLoggedIn, catchAsync(async (req, res) => {
const { id } = req.params;
const edittedBody = req.body;
edittedBody.timings = JSON.parse(edittedBody.timings);
let totalTime = 0;
for (let timing of edittedBody.timings) {
const timeDiff = calculateTimeDifference(timing.timingStart, timing.timingEnd);
totalTime += timeDiff;
}
edittedBody.duration = totalTime;
await Unit.findByIdAndUpdate(id, { $set: edittedBody });
res.redirect('/timetable/week/today');
}))
// ASSIGNMENT
//Hillclimbing function for Assignment
const hillclimbAssignment = require('./hillclimbing.js').hillclimbAssignment;
// POST make new assignment:
app.post('/assignments', validateIsLoggedIn, (async (req, res) => {
// Create new assignment unit:
var newAssignmentBody = req.body;
newAssignmentBody.userId = req.user.id;
newAssignmentBody.type = "Assignment";
newAssignmentBody.colour = "#696969";
newAssignmentBody.isAssigned = false;
const newAssignment = new Unit(newAssignmentBody);
await newAssignment.save();
// Assign task:
const assignedUnits = await Unit.find({userId: req.user.id, isAssigned: true});
newAssignmentBody._id = newAssignment.toObject()._id;
const optimalSchedule = hillclimbAssignment(assignedUnits, newAssignmentBody);
// Not enough timeslots to finish before deadline
if (optimalSchedule <= 0) {
res.sendStatus(401);
return;
}
for (let unit of optimalSchedule) {
if (!unit.isAssigned) {
unit.isAssigned = true;
await Unit.findByIdAndUpdate(unit._id.toString(), unit);
}
}
res.sendStatus(200);
}))
//PUT edit assignment
app.put('/assignments/:id', validateIsLoggedIn, (async (req, res) => {
const days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
const { id } = req.params;
const edittedBody = req.body;
edittedBody.timings = JSON.parse(edittedBody.timings);
for (let timing of edittedBody.timings) {
timing.day = days[new Date(timing.date).getDay()];
}
await Unit.findByIdAndUpdate(id, { $set: edittedBody });
res.redirect('/timetable/week/today');
}))
//POST nusmods import
app.post('/nus-mods', validateIsLoggedIn, catchAsync(async (req, res) => {
// Delete all existing modules first:
await Module.deleteMany({userId: req.user.id});
await Unit.deleteMany({userId: req.user.id});
const colourMapping = [
{'LEC': '#F1767A', 'REC': '#DE6569', 'LAB': '#DE6569', 'TUT': '#DE6569', 'SEC': '#DE6569'}, // Red
{'LEC': '#F99256', 'REC': '#E9874E', 'LAB': '#E9874E', 'TUT': '#E9874E', 'SEC': '#E9874E'}, // Orange
{'LEC': '#FECC67', 'REC': '#F6C665', 'LAB': '#F6C665', 'TUT': '#F6C665', 'SEC': '#F6C665'}, // Yellow
{'LEC': '#99CC98', 'REC': '#85B984', 'LAB': '#85B984', 'TUT': '#85B984', 'SEC': '#85B984'}, // Green
{'LEC': '#65CDCC', 'REC': '#5EC0BF', 'LAB': '#5EC0BF', 'TUT': '#5EC0BF', 'SEC': '#5EC0BF'}, // Turqoise
{'LEC': '#6499CC', 'REC': '#5B8DBD', 'LAB': '#5B8DBD', 'TUT': '#5B8DBD', 'SEC': '#5B8DBD'}, // Blue
{'LEC': '#CC99CD', 'REC': '#B887B9', 'LAB': '#B887B9', 'TUT': '#B887B9', 'SEC': '#B887B9'}, // Purple
{'LEC': '#D27B53', 'REC': '#C2724D', 'LAB': '#C2724D', 'TUT': '#C2724D', 'SEC': '#C2724D'} // Brown
];
let counter = 0;
// Add new modules:
const body = JSON.parse(req.body.newModules);
for (let newModuleBody of body) {
const moduleCode = newModuleBody.code;
const newModule = new Module({
userId: req.user.id,
code: moduleCode
});
await newModule.save();
const moduleId = newModule._id;
const moduleUnits = newModuleBody.units;
for (let moduleUnitBody of moduleUnits) {
const newUnit = new Unit({
userId: req.user.id,
moduleCode: moduleCode,
moduleId: moduleId,
class: moduleUnitBody.class,
type: moduleUnitBody.type,
timings: moduleUnitBody.timings,
colour: colourMapping[counter][moduleUnitBody.type]
})
await newUnit.save();
}
counter++;
if (counter >= colourMapping.length) {
counter = 0;
}
}
res.sendStatus(200);
}))
const optimise = require('./hillclimbing.js').optimise;
//Hillclimbing POST request:
app.post('/optimise', async (req, res) => {
const colourMapping = {
'#DE6569': '#FF8D99',
'#E9874E': '#FFAB80',
'#F6C665': '#FFD595',
'#85B984': '#A8E5AC',
'#5EC0BF': '#A0D6D4',
'#5B8DBD': '#93A2B9',
'#B887B9': '#CEB1C5',
'#C2724D': '#D38667'
};
try {
var modules = await Module.find({userId: req.user.id});
var units = [];
for (let module of modules) {
var moduleUnits = await Unit.find({moduleId: module._id.toString()});
for (let moduleUnit of moduleUnits) {
units.push(moduleUnit);
}
}
const { hours, semStartDate } = req.body;
const optimisedTasks = optimise(units, JSON.parse(hours), semStartDate);
for (let task of optimisedTasks) {
const newUnit = new Unit({
userId: req.user.id,
moduleCode: '[TASK] ' + task.moduleCode,
moduleId: task.moduleId,
class: task.class,
type: task.type,
timings: task.timings,
colour: colourMapping[task.colour]
})
await newUnit.save();
}
res.redirect('/timetable/week/today');
} catch (err) {
console.log(err);
res.redirect('/timetable/week/today');
}
})
//ACCOUNT PAGES:
//GET register page
app.get('/register', (req, res) => {
if (req.user) {
res.redirect('/timetable/week/today');
} else {
res.render('authentication/register', { registrationFailure: false });
}
});
// POST register
app.post('/register', async (req, res) => {
try {
const { email, username, password } = req.body;
const time = new Date();
const user = new User({ email, time, username });
await User.register(user, password);
// Automatically authenticate the user after successful registration
passport.authenticate('local')(req, res, () => {
res.redirect('/timetable/week/today');
});
} catch (err) {
console.log(err);
res.render('authentication/register', { registrationFailure: true });
}
});
//GET login page
app.get('/login', (req, res) => {
if (req.user) {
res.redirect('/timetable/week/today');
} else {
const loginFailure = req.query.failure;
res.render('authentication/login', { loginFailure });
}
})
//POST login
app.post('/login', passport.authenticate('local', { failureRedirect: '/login?failure=true' }), (req, res) => {
res.redirect('/timetable/week/today');
})
//GET logout
app.get('/logout', (req, res) => {
req.logout(function(err) {
if (err) { return next(err); }
res.redirect('/login');
});
});
//GET profile page
app.get('/profile', (req, res) => {
res.render('timetable/profile');
})
//POST change password
app.post('/change-password', (req, res) => {
// Ensure the user is authenticated
if (!req.isAuthenticated()) {
res.status(401).send('Unauthorized');
return;
}
try {
// Get the current user
const user = req.user;
// Get the new password from the request body
const newPassword = req.body.newPassword;
// Change the password using the Passport `setPassword` method
user.setPassword(newPassword, async () => {
// Save the updated user with the new password
await user.save();
res.send('Password changed successfully');
});
} catch (err) {
console.log(err);
res.status(500).send('Internal Server Error');
}
});
//No matching path
app.all('*', (req, res, next) => {
next(new ExpressError('Page Not Found', 404));
})
//Error handler
app.use((err, req, res, next) => {
const { statusCode = 500} = err;
if (!err.message) err.message = "Oh no! Something went wrong!";
res.status(statusCode).render('errors/error', { err});
})
const PORT = process.env.PORT | 8080
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
})
module.exports = app;