This repository was archived by the owner on Jul 18, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
407 lines (356 loc) · 12.1 KB
/
Copy pathindex.js
File metadata and controls
407 lines (356 loc) · 12.1 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
// Imports \\
const app = require('express')()
const http = require('http').createServer(app)
const bodyParser = require('body-parser')
const mongoose = require('mongoose')
const dotenv = require('dotenv').config()
const {OAuth2Client} = require('google-auth-library')
const oAuth2Client = new OAuth2Client(process.env.CLIENT_ID)
const fs = require("fs")
const md5 = require("./md5.js")
// Constants \\
const DBName = "data"
// Database \\
mongoose.connect(`mongodb+srv://GroupingApp:${process.env.DBPASS}@groupingapp.iz1de.mongodb.net/${DBName}?retryWrites=true&w=majority`, {useNewUrlParser: true, useUnifiedTopology: true})
const db = mongoose.connection
db.on('error', console.error.bind(console, 'Connection Error:'))
db.once('open', function() {
console.log("Connected to Database")
})
//Schema
const userSchema = new mongoose.Schema({
id: String,
classes: [
{
id: String,
name: String,
period: String,
preferences: [],
students: [
{
id: String,
first: String,
last: String,
middle: String,
email: String,
preferences: {
studentLike: [],
studentDislike: [],
topicLike: [],
topicDislike: [],
}
}
],
groupings: [
{
id: String,
name: String,
excluded: [],
groups: [[String]]
}
]
}
]
})
const User = mongoose.model("User", userSchema)
// Express \\
const sendFileOptions = {
root: __dirname + '/static',
dotfiles: 'deny'
}
app.use(bodyParser.json())
//Routing
app.get('/', async (req, res) => {
res.sendFile('/index.html', sendFileOptions)
})
app.get("/form/:userId/:classId", async (req, res) => {
const user = await User.findOne({id: req.params.userId}).exec()
if (user) {
const classObj = user.classes.find(c => c.id == req.params.classId)
if (classObj) {
res.sendFile('/form/index.html', sendFileOptions)
} else {
res.sendFile('/404/index.html', sendFileOptions)
}
} else {
res.sendFile('/404/index.html', sendFileOptions)
}
})
//Endpoints
app.get("/login", async (req, res) => {
const verification = await verifyUser(req.header("token"))
const user = await User.findOne({id: verification.user.sub}).exec()
if (verification.status && !user) {
new User({id: verification.user.sub}).save((e) => {
if (e) return console.log(e)
})
res.json({...verification, classes: []})
} else {
// console.log(user.classes[0].preferences)
// console.log(user.classes[0].students[0].preferences.studentLike[0].inputs)
// console.log(user.classes[0].students[0].preferences.topicLike[0].inputs)
res.json({...verification, classes: user.classes})
}
})
app.get("/formData", async (req, res) => {
const user = await User.findOne({id: req.query.user}).exec()
if (user) {
const classObj = user.classes.find(c => c.id == req.query.class)
if (classObj) {
res.json({status: true, preferences: classObj.preferences, className: classObj.name, period: classObj.period, students: classObj.students.map(s => (
{name: `${s.first} ${s.middle ? `${s.middle}. ` : ""}${s.last}`, id: md5(s.id)}
))})
} else {
res.json({status: false, error: "No Form Found"})
}
} else {
res.json({status: false, error: "No Form Found"})
}
})
app.post("/saveStudentPreferences", async (req, res) => {
const user = await User.findOne({id: req.body.userId, classes: {$elemMatch: {id: req.body.id}}}).exec()
if (user) {
const classObj = user.classes.find(c => c.id == req.body.id)
const student = classObj.students.find(s => s.id == req.body.studentId)
if (student) {
for (const preference of req.body.preferences) {
if (["studentLike", "studentDislike"].includes(preference.type)) {
preference.inputs = preference.inputs.map(id => classObj.students.find(s => id == md5(s.id)).id)
}
student.preferences[preference.type] = preference
}
await user.save()
res.json({status: true})
} else {
res.json({status: false, error: "No Student Found"})
}
} else {
res.json({status: false, error: "No Class Found"})
}
})
app.post("/addClasses", async (req, res) => {
const verification = await verifyUser(req.header("token"))
if (verification.status) {
const newClasses = []
for (const classObj of req.body.classObjs) {
if (!await User.findOne({id: verification.user.sub, classes: {$elemMatch: {id: classObj.id}}}).exec()) {
await User.updateOne({id: verification.user.sub}, {$push: {classes: classObj}})
newClasses.push(classObj)
}
}
if (newClasses.length) {
res.json({status: true, newClasses: newClasses})
} else {
res.json({status: false, error: "All Duplicate Classes - Make sure you are uploading new classes"})
}
}
})
app.post("/editClass", async (req, res) => {
const verification = await verifyUser(req.header("token"))
if (verification.status) {
const classObj = req.body.classObj
const user = await User.findOne({id: verification.user.sub, classes: {$elemMatch: {id: req.body.oldId}}}).exec()
if (user) {
const existingClassObj = user.classes.find(c => c.id == req.body.oldId)
existingClassObj.id = classObj.id
existingClassObj.name = classObj.name
existingClassObj.period = classObj.period
existingClassObj.students = classObj.students
await user.save()
res.json({status: true, updatedClass: existingClassObj})
} else {
res.json({status: false, error: "The class you are editing does not exist - Please reload"})
}
}
})
app.post("/deleteClass", async (req, res) => {
const verification = await verifyUser(req.header("token"))
if (verification.status) {
const user = await User.findOne({id: verification.user.sub, classes: {$elemMatch: {id: req.body.id}}}).exec()
if (user) {
user.classes.splice(user.classes.indexOf(user.classes.find(c => c.id == req.body.id)), 1)
await user.save()
res.json({status: true})
} else {
res.json({status: false, error: "No Class Found"})
}
}
})
app.post("/randomGroups", async (req, res) => {
const verification = await verifyUser(req.header("token"))
if (verification.status) {
const user = await User.findOne({id: verification.user.sub}).exec()
if (req.body.type == 0) {
res.json({status: true, groups: makeGroupsByNumGroups(user.classes.find(c => c.id == req.body.id).students.map(s => s.id).filter(s => !req.body.excluded.includes(s)), req.body.num)})
} else {
res.json({status: true, groups: makeGroupsByNumStudents(user.classes.find(c => c.id == req.body.id).students.map(s => s.id).filter(s => !req.body.excluded.includes(s)), req.body.num)})
}
}
})
app.post("/addGrouping", async (req, res) => {
const verification = await verifyUser(req.header("token"))
if (verification.status) {
const user = await User.findOne({id: verification.user.sub}).exec()
user.classes.find(c => c.id == req.body.id).groupings.push(req.body.grouping)
user.save()
res.json({status: true})
}
})
app.post("/editGrouping", async (req, res) => {
const verification = await verifyUser(req.header("token"))
if (verification.status) {
const user = await User.findOne({id: verification.user.sub}).exec()
const groupings = user.classes.find(c => c.id == req.body.id).groupings
groupings.splice(groupings.indexOf(groupings.find(g => g.id == req.body.oldId)), 1)
user.classes.find(c => c.id == req.body.id).groupings.push(req.body.grouping)
user.save()
res.json({status: true})
}
})
app.post("/deleteGroup", async (req, res) => {
const verification = await verifyUser(req.header("token"))
if (verification.status) {
const user = await User.findOne({id: verification.user.sub, classes: {$elemMatch: {id: req.body.id}}}).exec()
if (user) {
const groupings = user.classes.find(c => c.id == req.body.id).groupings
const grouping = groupings.find(g => g.id == req.body.groupingId)
if (grouping) {
groupings.splice(groupings.indexOf(grouping), 1)
await user.save()
res.json({status: true})
} else {
res.json({status: false, error: "No Group Found"})
}
} else {
res.json({status: false, error: "No Class Found"})
}
}
})
app.post("/addPreference", async (req, res) => {
const verification = await verifyUser(req.header("token"))
if (verification.status) {
const user = await User.findOne({id: verification.user.sub, classes: {$elemMatch: {id: req.body.id}}}).exec()
if (user) {
user.classes.find(c => c.id == req.body.id).preferences.push(req.body.preference)
await user.save()
res.json({status: true})
} else {
res.json({status: false, error: "No Class Found"})
}
}
})
app.post("/deletePreference", async (req, res) => {
const verification = await verifyUser(req.header("token"))
if (verification.status) {
const user = await User.findOne({id: verification.user.sub, classes: {$elemMatch: {id: req.body.id}}}).exec()
if (user) {
const preferences = user.classes.find(c => c.id == req.body.id).preferences
const preference = preferences.find(p => p.id == req.body.preferenceId)
if (preference) {
preferences.splice(preferences.indexOf(preference), 1)
await user.save()
res.json({status: true})
} else {
res.json({status: false, error: "No Preference Found"})
}
} else {
res.json({status: false, error: "No Class Found"})
}
}
})
app.use((req, res) => {
res.sendFile(req.url, sendFileOptions, (e) => {
if (e) {
res.status(404).sendFile('/404/index.html', sendFileOptions)
}
})
})
app
//Listen
http.listen(process.env.PORT, function(){
console.log(`Server listening on *:${process.env.PORT}`)
})
async function verifyUser(token) {
const ticket = await oAuth2Client.verifyIdToken({
idToken: token,
audience: process.env.CLIENT_ID
}).catch(e => {
return {status: false}
})
return {status: true, user: ticket.getPayload()}
}
function makeGroupsByNumGroups(students, numGroups) {
students = [...students]
let groups = []
for (let i = 0; i < numGroups; i++) {
groups.push([])
}
let counter = 0
while (students.length) {
const randomIndex = Math.floor(Math.random() * students.length)
groups[counter].push(students[randomIndex])
students.splice(randomIndex, 1)
counter = (counter+1) % groups.length
}
return groups
}
function makeGroupsByNumStudents(students, numStudents) {
students = [...students]
let groups = []
let numGroups = Math.floor(students.length/numStudents)
if ((students.length % numStudents > numStudents / 2 || students % numStudents > numGroups / 2)) {
numGroups += 1
}
for (let i = 0; i < numGroups; i++) {
groups.push([])
}
let counter = 0
while (students.length) {
const randomIndex = Math.floor(Math.random() * students.length)
groups[counter].push(students[randomIndex])
students.splice(randomIndex, 1)
counter = (counter+1) % groups.length
}
// const avg = groups.reduce((a, b) => a + b.length, 0) / groups.length
// console.log(avg)
// if (avg > numStudents + 0.5 || avg < numStudents - 0.5) {
// console.log("weird")
// }
return groups
}
// mean the #s group > groups of x => warning
// greater > x => Warning
// < Half > Merge last group
/*
User Schema
{
id: "user id",
classes: [
{
name: "class name",
period: "period number (as a string)",
students: [
{
id: "student id",
first: "first name",
middle: "middle initial",
last: "last name",
preferences: [
{
name: "name of preference"
type: integer representing type of preference (categorical, discrete, continuous),
value: "value of preference" //may change because may not always be a string (ex. rate 1-5)
}
]
}
]
groups: [
{
type: integer representing type of group (random etc),
groupings: [["student id"]]
}
]
}
]
}
*/