-
Notifications
You must be signed in to change notification settings - Fork 2
/
app.js
546 lines (469 loc) · 15.3 KB
/
app.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
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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
// initialize node app
var express = require("express");
var app = express();
var supabase = require("@supabase/supabase-js");
var bodyParser = require("body-parser");
var cookieParser = require("cookie-parser");
var base64buffer = require("base64-arraybuffer");
var structuredClone = require("structured-clone");
const https = require("https");
// load classes.json as allObjectsAvailable
var fs = require("fs");
var allObjectsAvailable = fs.readFileSync("classes.json");
allObjectsAvailable = JSON.parse(allObjectsAvailable);
// set up supabase
const supabaseUrl = process.env.SUPABASE_URL;
const supabaseKey = process.env.SUPABASE_KEY;
if (!supabaseKey || !supabaseKey) {
throw new Error("Please specify SUPABASE_URL and SUPABASE_KEY values in your environment.")
}
var supabase = supabase.createClient(supabaseUrl, supabaseKey);
const COMPETITION_COMPLETE = false;
app.set("view engine", "ejs");
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(bodyParser.json({ limit: "100mb" }));
function getRandomIndices(listOfObjects, counter = 5) {
var randomIndices = [];
for (var i = 0; i < counter; i++) {
if (listOfObjects.length == 0) {
break;
}
var randomIndex = Math.floor(Math.random() * listOfObjects.length);
if (listOfObjects[randomIndex] == undefined) {
randomIndex = Math.floor(Math.random() * listOfObjects.length);
}
randomIndices.push(listOfObjects[randomIndex]);
listOfObjects.splice(randomIndex, 1);
}
return randomIndices;
}
function assignObjects(found_classes) {
// remove found classes from allObjectsAvailable
var tier1 = allObjectsAvailable.tier1;
var tier2 = allObjectsAvailable.tier2;
var tier3 = allObjectsAvailable.tier3;
// remove found classes from allObjectsAvailable
var tier1 = tier1.filter(function (el) {
return !found_classes.includes(el);
});
var tier2 = tier2.filter(function (el) {
return !found_classes.includes(el);
});
var tier3 = tier3.filter(function (el) {
return !found_classes.includes(el);
});
var found_classes_count = 0;
var tiers = [tier1, tier2, tier3];
var classes_to_return = [];
for (var i = 0; i < tiers.length; i++) {
if (tiers[i].length > 0) {
var classes = getRandomIndices(tiers[i], 5 - found_classes_count);
// remove undefined
classes = classes.filter(function (el) {
return el != undefined;
});
if (classes.length == 5) {
return classes;
}
classes_to_return = classes_to_return.concat(classes);
found_classes_count += classes.length;
}
}
return classes_to_return;
}
app.post("/username", function (req, res) {
// set username in Supabase Users table
var username = req.body.uname;
// if username taken, add random 3 numbers to end
supabase
.from("Signups")
.select("*")
.eq("username", username)
.then(({ data, error }) => {
if (data.length > 0) {
username += "-" + Math.floor(Math.random() * 1000);
}
});
supabase
.from("Signups")
.update({ username: username })
.eq("user_id", req.cookies.user_id)
.then(({ data, error }) => {
res.cookie("username", username);
res.redirect("/leaderboard");
});
});
app.post("/register", async (req, res) => {
var email = req.body.email_create;
var password = req.body.create_pw;
// check if account exists
supabase
.from("Signups")
.select("*")
.eq("email", email)
.then(({ data, error }) => {
console.log(error)
if (data.length > 0) {
res.render("entry", {
user: null,
error: "An account with this email already exists",
scavenger_list: [],
});
} else {
supabase.auth
.signUp({
email: email,
password: password,
data: {
username: null,
},
})
.then(({ data, error }) => {
if (error) {
res.render("entry", { user: null, error: error.message });
res.send();
} else {
// make sure user isn't created
// insert into Signups table
supabase
.from("Signups")
.insert([
{
user_id: data.user.id,
email: email,
objects_identified: 0,
},
])
.then(({ data, error }) => {
return;
});
if (error) {
res.render("index", { user: null, error: error.message });
res.send();
} else {
res.cookie("start_time", new Date().getTime());
// assign objects
var tier1 = structuredClone(allObjectsAvailable.tier1);
var randomObjects = getRandomIndices(
tier1,
5
);
var items_to_add = [];
console.log(randomObjects.length)
// insert into Lists
for (var i = 0; i < randomObjects.length; i++) {
items_to_add.push({
user_id: data.user.id,
item_name: randomObjects[i],
found: false,
order: i,
batch_completed: false,
});
}
// console.log(items_to_add)
supabase
.from("Lists")
.insert(items_to_add)
.then(({ new_data, error }) => {
console.log(new_data)
res.cookie("user_id", data.user.id);
res.cookie("user_email", data.user.email);
res.cookie("new_user", true);
res.redirect("/");
});
}
}
});
}
});
});
app.post("/login", async function (req, res) {
var email = req.body.email;
var password = req.body.pw;
await supabase.auth
.signInWithPassword({
email: email,
password: password,
})
.then(({ data, error }) => {
if (error) {
res.render("entry", {
user: null,
error: error.message,
scavenger_list: [],
});
res.send();
} else {
res.cookie("user_id", data.user.id);
res.cookie("user_email", data.user.email);
res.redirect("/");
}
});
});
app.get("/logout", function (req, res) {
res.clearCookie("user_id");
res.clearCookie("user_email");
res.clearCookie("username");
res.redirect("/");
});
app.get("/leaderboard", function (req, res) {
// get all users if time_taken not null
supabase
.from("Signups")
.select("*")
.order("objects_identified", { ascending: true })
.then(({ data, error }) => {
if (error) {
res.render("user_leaderboard", {
error: error.message,
leaderboard: [],
user: req.cookies.user_email,
scavenger_list: [],
username: req.cookies.username || "",
email: req.cookies.user_email || "",
});
} else {
var leaderboard = data;
var user_in_leaderboard = data.filter(function (user) {
return user.username == req.cookies.username;
});
// sort leaderboard by objects_identified, descending
leaderboard.sort(function (a, b) {
return a.objects_identified - b.objects_identified;
});
var leaderboard = leaderboard.reverse()
res.render("user_leaderboard", {
error: null,
leaderboard: leaderboard,
user: req.cookies.user_email,
scavenger_list: [],
user_in_leaderboard: user_in_leaderboard,
time_taken: req.cookies.start_time,
username: req.cookies.username,
objects_identified: req.cookies.objects_identified,
username: req.cookies.username || "",
email: req.cookies.user_email || "",
});
}
});
});
async function update_batch (user_id) {
console.log("updating batch")
await supabase
.from("Lists")
.update({ batch_completed: true })
.eq("user_id", user_id);
}
app.post("/found", async (req, res) => {
var object_name = req.body.object;
var user_id = req.cookies.user_id;
await update_batch(req.cookies.user_id);
supabase
.from("Lists")
.update({ found: true, batch_completed: true })
.eq("user_id", user_id)
.eq("item_name", object_name)
.then(({ parent_data, error }) => {
// get count of remaining objects
supabase
.from("Lists")
.select("*")
.eq("user_id", user_id)
.then(({ data, error }) => {
// data = data.length;
var found_classes = data.filter(function (object) {
return object.found == false;
});
var count_found_classes = data.filter(function (object) {
return object.found == true;
}).length;
supabase
.from("Signups")
.update({ objects_identified: count_found_classes })
.eq("user_id", user_id)
.then(({ data, error }) => {
if (error) {
console.log(error);
}
console.log("updated signups");
});
});
});
supabase
.from("Lists")
.select("*")
.eq("user_id", user_id)
.then(({ data, error }) => {
var found_classes = data.filter(function (object) {
return object.found == false;
});
supabase
.from("Lists")
.select("*")
.eq("user_id", user_id)
.then(async function ({ data, error }) {
await insertObjects(data, req, found_classes, object_name).then(function (found_classes) {
res.body = { error: null };
res.send();
});
}
);
});
});
async function insertObjects (data, req, found_classes, last_found, override = false) {
var found_class_labels = data.filter(function (object) {
return object.found == true;
}).map(function (object) {
return object.item_name;
});
var found_classes_is_5_divisor = found_classes.length + 1 % 5 == 0;
if ((found_classes.length < 2 && !found_class_labels.includes(last_found)) || found_classes.length == 0 || override || found_classes_is_5_divisor) {
var found_classes = data.filter(function (object) {
return object.found == true;
});
// get list of object names from found classes
var found_classes_names = found_classes.map(function (object) {
return object.item_name;
});
console.log("found classes names");
console.log(found_classes_names);
var remainingObjectsAvailable = assignObjects(found_classes_names);
var items_to_add = [];
// insert into Lists
for (var i = 0; i < remainingObjectsAvailable.length; i++) {
items_to_add.push({
user_id: req.cookies.user_id,
item_name: remainingObjectsAvailable[i],
found: false,
order: i,
batch_completed: false,
});
}
await supabase
.from("Lists")
.insert(items_to_add);
}
return;
}
app.get("/", function (req, res) {
if (req.cookies && req.cookies.user_email) {
res.redirect("/play");
} else {
res.render("entry", { user: null, error: null, complete: COMPETITION_COMPLETE });
}
});
app.get("/play", function (req, res) {
if (req.cookies && req.cookies.user_email) {
var start_time = req.cookies.start_time;
supabase
.from("Lists")
.select("*")
.eq("user_id", req.cookies.user_id)
.then(({ data, error }) => {
var found_all = data.every(function (item) {
return item.found;
});
var batch_completed_count = data.every(function (item) {
return item.batch_completed;
});
// if user has found all objects but less than 25, assign new ones
// if (data.length < 2 && data.length < 25) {
// insertObjects(data, req, data, null, true);
// res.clearCookie("new_user");
// }
var found_any = data.some(function (item) {
return item.found && !item.batch_completed;
});
var objects_identified = data.filter(function (item) {
return item.found;
});
var new_user = req.cookies.new_user || false;
var level = 1;
// if any object is in tier2, say level 2
for (var i = 0; i < objects_identified.length; i++) {
if (allObjectsAvailable.tier2.includes(objects_identified[i].item_name)) {
level = 2;
} else if (allObjectsAvailable.tier3.includes(objects_identified[i].item_name)) {
level = 3;
}
}
var objects_identified = objects_identified.length;
var raffle_tickets_won = Math.floor(objects_identified / 5);
res.render("index", {
user: req.cookies.user_email,
error: null,
scavenger_list: data,
found_all: found_all,
found_any: found_any,
start_time: start_time,
username: req.cookies.username || "",
objects_identified: objects_identified,
raffle_tickets_won: raffle_tickets_won,
level: level,
new_user: new_user,
complete: COMPETITION_COMPLETE
});
});
} else {
res.redirect("/");
}
});
app.post("/image", async (req, res) => {
var image = req.body.image_data;
var x = req.body.x;
var y = req.body.y;
var w = req.body.w;
var h = req.body.h;
var image_class = req.body.image_class;
var file_name = image_class + "-" + x + "-" + y + "-" + w + "-" + h + ".jpeg";
var decoded = base64buffer.decode(image);
// post to Images
await supabase
.from("Images")
.insert([
{
user_id: req.cookies.user_id,
file_name: file_name,
class: image_class,
x: x,
y: y,
width: w,
height: h,
},
]);
supabase.storage
.from("images")
.upload(req.cookies.user_id + "-" + file_name, decoded, {
contentType: "image/jpeg",
})
.then(({ data, error }) => {});
res.body = { error: null };
res.send();
});
// app.get("/rules", function (req, res) {
// res.render("rules", { user: req.cookies.user_email, error: null });
// });
// app.get("/terms", function (req, res) {
// res.render("terms", { user: req.cookies.user_email, error: null });
// });
app.get("/offline", function (req, res) {
res.render("offline", { user: req.cookies.user_email, error: null });
});
app.get("/offline.html", function (req, res) {
res.render("offline", { user: req.cookies.user_email, error: null });
});
// start server
var port = process.env.PORT || 8087;
if (process.env.PROD) {
app.listen(port, function() {
console.log('Listening on ' + port);
});
} else {
console.log('Listening on ' + port);
https.createServer({
key: fs.readFileSync('/Users/james/localhost-key.pem'),
cert: fs.readFileSync('/Users/james/localhost.pem')
}, app).listen(port);
}