-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
1493 lines (1279 loc) · 40.4 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
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
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//All reqiure statements
require("dotenv").config();
require("./scripts/utils.js");
const session = require("express-session");
const express = require("express");
const Joi = require("joi");
const bcrypt = require("bcrypt");
const MongoStore = require("connect-mongo");
const multer = require("multer");
// configure multer for handling file uploads
const upload = multer({ dest: "uploads/" });
const fs = require("fs");
const { ClarifaiStub, grpc } = require("clarifai-nodejs-grpc");
const stub = ClarifaiStub.grpc();
const { Configuration, OpenAIApi } = require("openai");
// Salt rounds for bcrypt password hashing
const saltRounds = 12;
// For generating random id's
const { v4: uuidv4 } = require("uuid");
const he = require("he");
/* Secrets */
const mongodb_host = process.env.MONGODB_HOST;
const mongodb_user = process.env.MONGODB_USER;
const mongodb_password = process.env.MONGODB_PASSWORD;
const mongodb_database = process.env.MONGODB_DATABASE;
const mongodb_session_secret = process.env.MONGODB_SESSION_SECRET;
const node_session_secret = process.env.NODE_SESSION_SECRET;
const clarifai_secret = process.env.CLARIFAI_SECRET;
const openai_secret = process.env.OPENAI_SECRET;
//OpenAI
const configuration = new Configuration({
apiKey: openai_secret,
});
const openai = new OpenAIApi(configuration);
//Express
const app = express();
//hosting port
const port = process.env.PORT || 3090;
//session expire time
const expire = 60 * 60 * 60 * 1000;
// mongodb connection
var { database } = include("dbConnection");
//accessing user collection
const userCollection = database.db(mongodb_database).collection("users");
//accessing recipe collection
const recipesCollection = database.db(mongodb_database).collection("recipes");
//accessing comment collection
const commentCollection = database.db(mongodb_database).collection("comments");
//accessing recipeUpload collection
const recipeUploadCollection = database
.db(mongodb_database)
.collection("recipeUpload");
//accessing pantry collection
const pantryCollection = database.db(mongodb_database).collection("pantry");
/* setting up file usage */
app.set("view engine", "ejs");
app.use(express.urlencoded({ extended: false }));
app.use("/public/images/", express.static("./public/images"));
app.use("/json", express.static("./json"));
app.use("/styles", express.static("./styles"));
app.use(express.static("./scripts"));
// use for session storage
var mongoStore = MongoStore.create({
mongoUrl: `mongodb+srv://${mongodb_user}:${mongodb_password}@${mongodb_host}/Recipal`,
crypto: {
secret: mongodb_session_secret,
},
});
function isValidSession(req) {
if (req.session.authenticated) {
return true;
}
return false;
}
function sessionValidation(req, res) {
if (!isValidSession(req)) {
res.redirect("/login");
}
}
// use node session
app.use(
session({
secret: node_session_secret,
store: mongoStore,
saveUninitialized: false,
resave: true,
})
);
// landing page
app.get("/", (req, res) => {
if (isValidSession(req)) {
res.redirect("/home");
return;
}
res.render("index");
});
//login page
app.get("/login", (req, res) => {
res.render("login");
});
// processing login request
app.post("/loggingin", async (req, res) => {
var email = req.body.email;
var password = req.body.password;
const schema = Joi.string().required();
const validationResult = schema.validate(email);
if (validationResult.error != null) {
console.log(validationResult.error);
res.render("login-invalid");
return;
}
const result = await userCollection
.find({ email: email })
.project({ email: 1, password: 1, _id: 1 })
.toArray();
if (result.length != 1) {
console.log("Email not found");
res.render("login-invalid");
return;
}
if (await bcrypt.compare(password, result[0].password)) {
req.session.authenticated = true;
req.session.email = email;
req.session.cookie.maxAge = expire;
res.redirect("/home");
return;
} else {
res.render("login-invalid");
return;
}
});
// perform logout, and delete session
app.get("/logout", (req, res) => {
req.session.destroy();
res.redirect("/home");
});
//sign up page
app.get("/signup", (req, res) => {
res.render("signup");
});
//Process new user signup
app.post("/createUser", async (req, res) => {
var username = req.body.username;
var email = req.body.email;
var password = req.body.password;
if (!req.body.username || req.body.username.trim() === "") {
res.redirect("/signup");
return;
}
if (!req.body.email || req.body.email.trim() === "") {
res.redirect("/signup");
return;
}
if (!req.body.password || req.body.password.trim() === "") {
res.redirect("/signup");
return;
}
//Validating using Joi
const schema = Joi.object({
username: Joi.string().alphanum().max(20).required(),
email: Joi.string().max(20).required(),
password: Joi.string().max(20).required(),
});
const validationResultName = schema.validate({ username, email, password });
if (validationResultName.error != null) {
console.log(validationResultName.error);
res.redirect("/signup");
return;
}
//Hashing Password
var hashedPassword = await bcrypt.hash(password, 12);
const allergens = [];
const diet = [];
const shoppinglist = [];
var result = await userCollection.find({ email: email }).toArray();
if (result.length == 0) {
await userCollection.insertOne({
username: username,
email: email,
password: hashedPassword,
allergens: allergens,
diet: diet,
shoppinglist: shoppinglist,
favourite: [],
});
} else {
res.render("signupEmailTaken");
return;
}
//authenticating session
req.session.authenticated = true;
req.session.email = email;
req.session.cookie.maxAge = expire;
res.redirect("security");
});
// prompting for security questions
app.get("/security", async (req, res) => {
res.render("security");
});
//processing user security questions, insert into database
app.post("/securityRecovery", async (req, res) => {
var securityPassword = req.body.securityPassword;
var securityQuestion = req.body.securityQuestion;
console.log(req.body);
if (!req.body.securityPassword || req.body.securityPassword.trim() === "") {
res.redirect("/security");
return;
}
const schema = Joi.object({
securityPassword: Joi.string().max(20).required(),
});
const validationResultName = schema.validate({ securityPassword });
if (validationResultName.error != null) {
console.log(validationResultName.error);
res.redirect("security");
return;
}
var hashedPassword = await bcrypt.hash(securityPassword, 12);
await userCollection.updateOne(
{ email: req.session.email },
{ $set: { securityPassword: hashedPassword } }
);
await userCollection.updateOne(
{ email: req.session.email },
{ $set: { securityQuestion: securityQuestion } }
);
res.redirect("/signupDiet");
});
//Ask user to add preferences on signup
app.get("/signupDiet", (req, res) => {
res.render("signupDiet");
});
//post users preferences
app.post("/userDiet", async (req, res) => {
var diet = req.body.diet;
console.log(diet);
await userCollection.updateOne(
{ email: req.session.email },
{ $push: { diet: diet } }
);
res.redirect("/signupAllergens");
});
app.get("/signupAllergens", (req, res) => {
res.render("signupAllergens");
});
app.post("/userAllergens", async (req, res) => {
const allergies = req.body.allergy;
const filteredAllergies = allergies.filter((allergy) => allergy !== "");
try {
const updateQuery = { $push: { allergens: { $each: filteredAllergies } } };
await userCollection.updateOne({ email: req.session.email }, updateQuery);
res.redirect("/home");
} catch (err) {
console.error(err);
res.status(500).send("Failed to save preferences");
}
});
//password reset page
app.get("/forgot", async (req, res) => {
res.render("forgot");
});
app.post("/forgotLogin", async (req, res) => {
var email = req.body.email;
if (!req.body.email || req.body.email.trim() === "") {
res.render("forgotInvalid");
return;
}
const schema = Joi.string().required();
const validationResult = schema.validate(email);
if (validationResult.error != null) {
console.log(validationResult.error);
res.render("forgotInvalid");
return;
}
const result = await userCollection
.find({ email: email })
.project({ securityQuestion: 1, securityPassword: 1, _id: 1 })
.toArray();
if (result.length != 1) {
res.render("forgotInvalid");
return;
}
let sQuestion = result[0].securityQuestion;
let sPassword = result[0].securityPassword;
let account = [sQuestion, sPassword];
req.session.email = email;
var question = "";
if (sQuestion == 1) {
question = "What is the middle name of your youngest child?";
} else if (sQuestion == 2) {
question = "What is name of your first stuffed animal?";
} else if (sQuestion == 3) {
question = "What city/town did your mother and father meet?";
}
res.render("verify", { account: account, question });
});
// Verifying security question password for resetting password.
app.post("/securityPasswordVerify", async (req, res) => {
var password = req.body.password;
email = req.session.email;
const result = await userCollection
.find({ email: email })
.project({ securityQuestion: 1, securityPassword: 1, _id: 1 })
.toArray();
let sQuestion = result[0].securityQuestion;
var question = "";
if (sQuestion == 1) {
question = "What is the middle name of your youngest child?";
} else if (sQuestion == 2) {
question = "What is name of your first stuffed animal?";
} else if (sQuestion == 3) {
question = "What city/town did your mother and father meet?";
}
const schema = Joi.object({
password: Joi.string().max(20).required(),
});
const validationResultName = schema.validate({ password });
if (validationResultName.error != null) {
console.log(validationResultName.error);
res.render("verifyInvalid", { question });
return;
}
if (await bcrypt.compare(password, result[0].securityPassword)) {
req.session.authenticated = true;
req.session.email = email;
req.session.cookie.maxAge = expire;
res.render("changePassword");
return;
} else {
res.render("verifyInvalid", { question });
}
});
//Reset the users password
app.post("/securityChangePassword", async (req, res) => {
var password = req.body.password;
if (!req.body.password || req.body.password.trim() === "") {
res.render("changePassword");
return;
}
const schema = Joi.object({
password: Joi.string().max(20).required(),
});
const validationResultName = schema.validate({ password });
if (validationResultName.error != null) {
console.log(validationResultName.error);
res.render("changePassword");
return;
}
var hashedPassword = await bcrypt.hash(password, 12);
await userCollection.updateOne(
{ email: req.session.email },
{ $set: { password: hashedPassword } }
);
res.redirect("/home");
});
//Display users' profile page
app.get("/profile", async (req, res) => {
sessionValidation(req, res);
const email = req.session.email;
const result = await userCollection
.find({ email: email })
.project({ username: 1, password: 1, _id: 1, email: 1 })
.toArray();
res.render("profile", {
tabContent: "profile-info",
user: result[0],
pantry: null,
});
});
//Preferences tab for user profile page
app.get("/profile/preferences", async (req, res) => {
sessionValidation(req, res);
const email = req.session.email;
const result = await userCollection
.find({ email: email })
.project({ allergens: 1, diet: 1, username: 1 })
.toArray();
res.render("profile", {
tabContent: "preferences",
user: result[0],
pantry: null,
});
});
//Pantry tab for user profile page
app.get("/profile/pantry", async (req, res) => {
const email = req.session.email;
const result = await userCollection
.find({ email: email })
.project({ username: 1, password: 1, _id: 1, email: 1 })
.toArray();
const result2 = await pantryCollection
.find({ email: email })
.project({ item: 1 })
.toArray();
res.render("profile", {
tabContent: "pantry",
user: result[0],
pantry: result2,
});
});
//Saves ingredient input to user pantry
app.post("/savePantry", async (req, res) => {
const email = req.session.email;
const pantry = req.body.pantry;
await pantryCollection.insertOne({ email: email, item: pantry });
res.redirect("/profile/pantry");
});
//Delete item from user pantry
app.post("/deletePantry", async (req, res) => {
const email = req.session.email;
const item = req.body.item;
pantryCollection.deleteOne({ email: email, item: item });
res.redirect("/profile/pantry");
});
//Save the users dietary and
app.post("/savePreferences", async (req, res) => {
const allergies = req.body.allergy;
const diet = req.body.diet;
console.log(allergies);
//Creating a new array without any empty strings
const filteredAllergies = allergies.filter((allergy) => allergy !== "");
try {
const updateQuery = { $push: { allergens: { $each: filteredAllergies } } };
if (diet.length > 0) {
updateQuery.$push.diet = diet;
}
await userCollection.updateOne({ email: req.session.email }, updateQuery);
res.render("preferencesSaved");
} catch (err) {
console.error(err);
res.status(500).send("Failed to save preferences");
}
});
//Delete either allergen or diet restriction from profile.
app.post("/preferences/delete", async (req, res) => {
const email = req.session.email;
const type = req.body.type;
const value = req.body.value;
let updateField = null;
if (type === "allergens") {
updateField = { $pull: { allergens: value } };
} else if (type === "diet") {
updateField = { $pull: { diet: value } };
} else {
res.status(400).send("Invalid type parameter");
return;
}
try {
await userCollection.updateOne({ email: email }, updateField);
res.redirect("/profile/preferences");
} catch (err) {
console.error(err);
res.status(500).send("Failed to delete value");
}
});
//HomePage
app.get("/home", async (req, res) => {
const searchQuery = req.query.q;
const query = {}; // You can customize the query to filter specific recipes if needed
try {
const [recipeCount, recipeData] = await Promise.all([
recipeUploadCollection.countDocuments(query),
recipeUploadCollection
.find(query)
.project({
name: 1,
servings: 1,
ingredients: 1,
steps: 1,
description: 1,
_id: 1,
})
.toArray(),
]);
var headerSession = "";
if (!isValidSession(req)) {
headerSession = "BeforeLogin";
}
res.render("homepage", {
headerSession,
searchQuery,
recipe: recipeData,
});
} catch (error) {
console.error("Error retrieving recipe data:", error);
// Handle the error accordingly
res.render("errorPage");
}
});
//Search page with recipes and search query
app.get("/search", async (req, res) => {
const userEmail = req.session.email;
const user = await userCollection.findOne({ email: req.session.email });
var headerSession = "";
if (!isValidSession(req)) {
headerSession = "BeforeLogin";
}
//array for passing names for checkboxes
const availableOptions = [
"dinner",
"dessert",
"lunch",
"breakfast",
"appetizer",
"low-calorie",
];
if (isValidSession(req)) {
var allergens = user.allergens;
var diet = user.diet;
}
//array for passing checkbox filters into ejs
const meal = ["dinner", "dessert", "lunch", "breakfast", "appetizer"];
const cuisine = [
"italian",
"mexican",
"caribbean",
"french",
"moroccan",
"english",
"southern",
"indian",
];
const dietType = [
"gluten-free",
"vegan",
"vegetarian",
"low-sodium",
"low-calorie",
"low-fat",
"low-carb",
];
const excludeDiet = req.query.excludeDiet === "on";
console.log(excludeDiet);
const mealFilter = req.query.m;
const cuisineFilter = req.query.c;
const searchQuery = req.query.q;
const searchTerm = req.query.q;
var dietFilter = [];
// ensuring filters are stored in an array
if (!excludeDiet) {
dietFilter = diet ? [...diet] : [];
}
console.log(dietFilter);
if (Array.isArray(req.query.d)) {
dietFilter.push(...req.query.d);
} else if (req.query.d) {
dietFilter.push(req.query.d);
}
console.log(dietFilter);
const selectedCategories = [];
if (mealFilter) {
if (Array.isArray(mealFilter)) {
selectedCategories.push(...mealFilter);
} else {
selectedCategories.push(mealFilter);
}
}
if (cuisineFilter) {
if (Array.isArray(cuisineFilter)) {
selectedCategories.push(...cuisineFilter);
} else {
selectedCategories.push(cuisineFilter);
}
}
if (dietFilter) {
if (Array.isArray(dietFilter)) {
selectedCategories.push(...dietFilter);
} else {
selectedCategories.push(dietFilter);
}
}
const searchIngredients = searchQuery ? searchQuery.split(",") : [];
const page = parseInt(req.query.page) || 1;
const recipesPerPage = 20;
const skip = (page - 1) * recipesPerPage;
//Easter Egg
var conrad = false;
var bread = false;
for (let i = 0; i < searchIngredients.length; i++) {
let currIngredient = searchIngredients[i].trim().toLowerCase();
if (currIngredient === "conrad") {
conrad = true;
}
if (currIngredient === "bread") {
bread = true;
}
if (conrad && bread) {
res.render("conrad", { headerSession });
return;
}
}
/*Define Query for recipe database */
const query = {};
if (mealFilter && mealFilter.length > 0) {
let termQuery;
if (Array.isArray(mealFilter)) {
termQuery = mealFilter.map((term) => ({
search_terms: new RegExp(term, "i"),
}));
} else {
termQuery = [{ search_terms: new RegExp(mealFilter, "i") }];
}
query.$and = query.$and || [];
query.$and.push({ $or: termQuery });
}
if (cuisineFilter && cuisineFilter.length > 0) {
let termQuery;
if (Array.isArray(cuisineFilter)) {
termQuery = cuisineFilter.map((term) => ({
search_terms: new RegExp(term, "i"),
}));
} else {
termQuery = [{ search_terms: new RegExp(cuisineFilter, "i") }];
}
query.$and = query.$and || [];
query.$and.push({ $or: termQuery });
}
if (searchTerm && searchTerm.length > 0) {
const recipeQuery = { name: { $regex: new RegExp(searchTerm, "i") } };
query.$or = query.$and || [];
query.$or.push(recipeQuery);
}
if (searchIngredients.length > 0) {
const ingredientQueries = searchIngredients.map((ingredient) => ({
ingredients: { $regex: new RegExp(ingredient, "i") },
}));
query.$or = query.$or || [];
query.$or.push({ $and: ingredientQueries });
}
if (allergens && allergens.length > 0) {
const allergenQuery = allergens.map((allergen) => ({
ingredients: { $not: new RegExp(allergen, "i") },
}));
query.$and = query.$and || [];
query.$and.push({ $and: allergenQuery });
}
if (dietFilter && dietFilter.length > 0) {
const dietQuery = dietFilter.map((tag) => ({
search_terms: { $regex: new RegExp(tag, "i") },
}));
query.$and = query.$and || [];
query.$and.push({ $and: dietQuery });
}
const countPromise = recipesCollection.countDocuments(query);
/* End of recipe query */
const recipesPromise = recipesCollection
.find(query)
.project({ name: 1, description: 1, servings: 1, _id: 1, ingredients: 1 })
.skip(skip)
.limit(recipesPerPage)
.toArray();
const [recipeCount, recipeData] = await Promise.all([
countPromise,
recipesPromise,
]);
const pageCount = Math.ceil(recipeCount / recipesPerPage);
const maxButtons = 10;
const visiblePages = 5;
const halfVisiblePages = Math.floor(visiblePages / 2);
let startPage = Math.max(1, page - halfVisiblePages);
let endPage = Math.min(startPage + visiblePages - 1, pageCount);
if (endPage - startPage + 1 < visiblePages) {
startPage = Math.max(1, endPage - visiblePages + 1);
}
//recieved all ratings
var ratings = await commentCollection
.find({})
.project({ rating: 1, recipeID: 1 })
.toArray();
//filters the ratings
var filteredRatings = [];
for (count = 0; ratings.length > count; count++) {
//ignores all null or empty ratings
if (!(ratings[count].rating == null)) {
//compares filteredRatings array object to object in ratings array
if (filteredRatings.some((e) => e.recipeID == ratings[count].recipeID)) {
key = "recipeID";
value = ratings[count].recipeID;
//Function to find index based off key and value developed by ChatGPT
function findIndex(array, key, value) {
for (let index = 0; index < array.length; index++) {
const obj = array[index];
if (obj.hasOwnProperty(key) && obj[key] === value) {
return index;
}
}
}
objIndex = findIndex(filteredRatings, key, value);
//Adds integer of rating together and total amount of ratings for average calculation later on
filteredRatings[objIndex].rating =
parseInt(filteredRatings[objIndex].rating) +
parseInt(ratings[count].rating);
filteredRatings[objIndex].ratingTotal =
parseInt(filteredRatings[objIndex].ratingTotal) + parseInt(1);
} else {
//If there is no unique recipeID in filtered ratings array, the object is added
filteredRatings.push({
recipeID: ratings[count].recipeID,
rating: parseInt(ratings[count].rating),
ratingTotal: parseInt(1),
});
}
}
}
recipeData.forEach((recipe) => {
recipe.name = he.decode(recipe.name); // fixes html encoding issue
if (recipe.description && recipe.description.length > 160) {
recipe.description = recipe.description.substring(0, 160) + "...";
}
});
const pages = Array.from(
{ length: endPage - startPage + 1 },
(_, i) => startPage + i
);
res.render("search", {
recipe: recipeData,
currentPage: page,
pageCount: pageCount,
pages: pages,
maxButtons: maxButtons,
visiblePages: visiblePages,
startPage: startPage,
searchQuery: searchQuery,
searchIngredients: searchIngredients,
filteredRatings,
headerSession,
selectedCategories: selectedCategories,
meal: meal,
cuisine: cuisine,
dietType: dietType,
excludeDiet: excludeDiet,
userEmail,
user,
});
});
// recipe detail page
const { ObjectId } = require("mongodb");
app.get("/recipe", async (req, res) => {
const recipeId = req.query.id;
const commentData = await commentCollection
.find({ recipeID: recipeId })
.project({ commentHeader: 1, username: 1, comment: 1, rating: 1 })
.toArray();
const recipeData = await recipesCollection.findOne({
_id: new ObjectId(recipeId),
});
if (!recipeData) {
res.send("Recipe not found");
return;
}
//recieved all ratings
var ratings = await commentCollection
.find({})
.project({ rating: 1, recipeID: 1 })
.toArray();
//Same code as in homepage to display rating avg in recipe page
var filteredRatings = [];
for (count = 0; ratings.length > count; count++) {
//ignores all null or empty ratings
if (!(ratings[count].rating == null)) {
//compares filteredRatings array object to object in ratings array
if (filteredRatings.some((e) => e.recipeID == ratings[count].recipeID)) {
key = "recipeID";
value = ratings[count].recipeID;
//Function to find index based off key and value developed by ChatGPT
function findIndex(array, key, value) {
for (let index = 0; index < array.length; index++) {
const obj = array[index];
if (obj.hasOwnProperty(key) && obj[key] === value) {
return index;
}
}
}
objIndex = findIndex(filteredRatings, key, value);
//Adds integer of rating together and total amount of ratings for average calculation later on
filteredRatings[objIndex].rating =
parseInt(filteredRatings[objIndex].rating) +
parseInt(ratings[count].rating);
filteredRatings[objIndex].ratingTotal =
parseInt(filteredRatings[objIndex].ratingTotal) + parseInt(1);
} else {
//If there is no unique recipeID in filtered ratings array, the object is added
filteredRatings.push({
recipeID: ratings[count].recipeID,
rating: parseInt(ratings[count].rating),
ratingTotal: parseInt(1),
});
}
}
}
var headerSession = "";
if (!isValidSession(req)) {
headerSession = "BeforeLogin";
}
recipeData.name = he.decode(recipeData.name);
recipeData.steps = he.decode(recipeData.steps);
if (recipeData.description) {
recipeData.description = he.decode(recipeData.description);
}
recipeData.ingredients_raw_str = he.decode(recipeData.ingredients_raw_str);
res.render("recipe", {
recipe: recipeData,
commentData: commentData,
filteredRatings: filteredRatings,
headerSession,
});
});
//Post comment to database
app.post("/commentPost", async (req, res) => {
if (!isValidSession(req)) {
res.redirect("login");
return;
} else {
var email = req.session.email;
var comment = req.body.comment;
var recipeID = req.body.idRecipe;
var header = req.body.commentHeader;
var rating = req.body.rating;
const resultUser = await userCollection
.find({ email: email })
.project({ username: 1 })
.toArray();
var username = resultUser[0].username;
await commentCollection.insertOne({
recipeID: recipeID,
username: username,
commentHeader: header,
comment: comment,
rating: rating,
});
res.redirect(`/recipe?id=${recipeID}`);
}
});
// browse recipe page (redirect from homepage)
app.get("/browseRecipe/:id", async (req, res) => {
if (!isValidSession(req)) {
headerSession = "BeforeLogin";
}
const userEmail = req.session.email;
const user = await userCollection.findOne({ email: userEmail });
const recipesPerPage = 20;
const page = req.params.id;
let query = {}; // Initialize an empty query object
let specificTag = ""; // Specify the default tag value
let title = "";
if (page == 1) {
specificTag = "30-minutes-or-less";
title = "30-minutes-or-less Recipes";
} else if (page == 2) {
specificTag = "low-calorie";
title = "Low-calories Recipes";
} else if (page == 3) {
specificTag = "occasion";
title = "Recipes of the day";
} else if (page == 4) {
specificTag = "breakfast";