-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
1768 lines (1637 loc) · 58.6 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
"use strict";
const express = require("express");
const fetch = require("node-fetch");
const request = require("request");
const bodyParser = require("body-parser");
let keys = {};
try {
keys = require("./keys");
} catch (error) {
console.log("Keys.js file not found");
}
//const functions = require(".functions");
//const variables = require("./variablkeyses");
const nutrietnsURL = "https://trackapi.nutritionix.com/v2/natural/nutrients";
// ===================================================================================================================//
// === PARAMETERS ====================================================================================================//
// ===================================================================================================================//
const averageDailyCalories = 2200;
const proteinsDaily = 50; // grams, http://www.mydailyintake.net/daily-intake-levels/
const fatsDaily = 70; // grams, http://www.mydailyintake.net/daily-intake-levels/
const carbsDaily = 310; // grams, http://www.mydailyintake.net/daily-intake-levels/
const sugarsDaily = 90; // grams, http://www.mydailyintake.net/daily-intake-levels/
const protCalPerG = 4; // calories per 1g, http://healthyeating.sfgate.com/gram-protein-carbohydrates-contains-many-kilocalories-5978.html
const fatCalPerG = 9; // calories per 1g, http://healthyeating.sfgate.com/gram-protein-carbohydrates-contains-many-kilocalories-5978.html
const carbCalPerG = 4; // calories per 1g, http://healthyeating.sfgate.com/gram-protein-carbohydrates-contains-many-kilocalories-5978.html
let context = ""; // here we store the name of the last "block" that was triggered; depending on context, user's input
// may be handled differently
const expression = /[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi;
const regex = new RegExp(expression);
let app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.listen(process.env.PORT || 5000, function() {
console.log("FitmohBot: Webhook server is listening, port 5000");
});
// Server index page
app.get("/", (req, res) => {
res.send(
"FitmohBot"
);
});
// Facebook Webhook
// Used for verification
app.get("/webhook", function(req, res) {
if (
req.query["hub.verify_token"] === (process.env.fbVerifyToken || keys.fbVerifyToken)
) {
console.log("Fitmoh: Webhook verified");
res.status(200).send(req.query["hub.challenge"]);
} else {
console.error(
"Fitmoh: Verification failed. Tokens do not match."
);
res.sendStatus(403);
}
});
// All callbacks for Messenger will be POST-ed here
app.post("/webhook", (req, res) => {
// Make sure this is a page subscription
if (req.body.object == "page") {
// Iterate over each entry
// There may be multiple entries if batched
//#console.log(JSON.stringify(req.body.entry));
req.body.entry.forEach(entry => {
// Iterate over each messaging event
if (entry.messaging) {
let userInput = {
type: "other", // by default
payload: null
};
entry.messaging.forEach(event => {
let senderId = event.sender.id;
console.log(`\nEVENT: ${JSON.stringify(event)}`);
if (event.message) {
// User entered text
if (
event.message.text &&
!event.message.quick_reply &&
!event.message.is_echo
) {
userInput = {
type: "text",
payload: event.message.text
};
// User clicked quick response button
} else if (event.message.quick_reply) {
userInput = {
type: "buttonClick",
payload: event.message.quick_reply.payload
};
// User uploaded something
} else if (event.message.attachments) {
// Which is an image
if (
event.message.attachments[0].type === "image" &&
!event.message.attachments[0].payload.sticker_id
) {
userInput = {
type: "image",
payload: event.message.attachments[0].payload.url
};
}
// Other input types
} else {
userInput = {
type: "other",
payload: null
};
}
console.log(`\nuserInput: ${JSON.stringify(userInput)}`);
if (!event.message.is_echo) {
// Needn't react to bot's messages
console.log(userInput);
processMessage(senderId, userInput);
}
// Getting started and persistent menu buttons
} else if (event.postback) {
if (event.postback.payload === "GETTING_STARTED") {
userInput = {
type: "buttonClick",
payload: "GETTING_STARTED"
};
} else if (event.postback.payload === "NEEDHELP") {
userInput = {
type: "buttonClick",
payload: "NEEDHELP"
};
}
processMessage(senderId, userInput);
}
});
}
});
res.status(200).end();
}
});
// Main conversation flow function
async function processMessage(senderId, userInput) {
// Main dialog flow
// IMAGE UPLOADS are handled here
if (userInput.type == "image") {
try {
await typingOnOff(senderId, 5);
await send_text_message(senderId, "Image received. Let me analyse it...");
let imgBase64 = await imgToBase64(userInput.payload);
let imgLabels = await googleVisionBase64(imgBase64);
await typingOnOff(senderId, 3);
await send_text_message(senderId, "Done");
await typingOnOff(senderId, 3);
if (imgLabels.length > 0) {
await send_text_message(
senderId,
`My best guess that it's:\n\n${imgLabels[0].toUpperCase()}`
);
let quickButtons = {
Correct: `LABEL:${imgLabels[0]}`,
"My variant": `LABEL:USERDEFINES`
};
if (imgLabels.length > 1) {
for (let label of imgLabels.slice(1)) {
quickButtons[label] = `LABEL:${label}`;
}
}
await typingOnOff(senderId, 3);
await send_quick_replies_msg(
senderId,
"Is that right? Please confirm, choose another variant from my guesses or enter your own variant",
quickButtons
);
context = "User picks up a label";
} else {
// No labels were picked up
await send_text_message(
senderId,
"Unfortunately I failed to pick up any terms for this image. Are you sure it's Ok? Maybe try with a different one?"
);
}
} catch (error) {
await send_text_message(
senderId,
"Unfortunately I failed to pick up any terms for this image. Are you sure it's Ok? Maybe try with a different one?"
);
await typingOnOff(senderId, 3);
await send_text_message(
senderId,
"Feel free to give me another photo of food/URL to a photo of food or just a name of food ;)"
);
}
// BUTTON CLICKS are handled here
} else if (userInput.type == "buttonClick") {
console.log("Button click");
try {
if (context == "User picks up a label") {
let foodLabel = userInput.payload.slice(6);
if (foodLabel != "USERDEFINES") {
let quickButtons = {
Calories: `NUTRDATA#${foodLabel}#CALORIES`,
"Proteins/Fats/Carbs": `NUTRDATA#${foodLabel}#NUTRIENTS`,
Vitamins: `NUTRDATA#${foodLabel}#VITAMINS`,
"All together": `NUTRDATA#${foodLabel}#ALL`
};
await typingOnOff(senderId, 3);
context = "What data to display";
await send_quick_replies_msg(
senderId,
`What nutrient data for ${foodLabel} are you interested in?`,
quickButtons
);
} else {
context = "Awaiting user's label";
await send_text_message(
senderId,
"Ok. Please type in what do you think is shown on this photo"
);
}
} else if (context == "What data to display") {
let nutrDataNeeded = userInput.payload.split("#")[2];
let foodToAnalyse = userInput.payload.split("#")[1];
if (nutrDataNeeded == "CALORIES") {
let caloriesData = await caloriesSummary(foodToAnalyse);
caloriesData += "\n\nAnything else?";
await typingOnOff(senderId, 3);
let quickButtons = {
"Proteins/Fats/Carbs": `NUTRDATA#${foodToAnalyse}#NUTRIENTS`,
Vitamins: `NUTRDATA#${foodToAnalyse}#VITAMINS`,
"All together": `NUTRDATA#${foodToAnalyse}#ALL`
};
await send_quick_replies_msg(senderId, caloriesData, quickButtons);
} else if (nutrDataNeeded == "NUTRIENTS") {
let nutrData = await protFatsCarbsSummary(foodToAnalyse);
nutrData += "\n\nAnything else?";
await typingOnOff(senderId, 3);
let quickButtons = {
Calories: `NUTRDATA#${foodToAnalyse}#CALORIES`,
Vitamins: `NUTRDATA#${foodToAnalyse}#VITAMINS`,
"All together": `NUTRDATA#${foodToAnalyse}#ALL`
};
await send_quick_replies_msg(senderId, nutrData, quickButtons);
} else if (nutrDataNeeded == "VITAMINS") {
let vitaminData = await vitaminsSummary(foodToAnalyse);
vitaminData += "\n\nAnything else?";
await typingOnOff(senderId, 3);
let quickButtons = {
Calories: `NUTRDATA#${foodToAnalyse}#CALORIES`,
"Proteins/Fats/Carbs": `NUTRDATA#${foodToAnalyse}#NUTRIENTS`,
"All together": `NUTRDATA#${foodToAnalyse}#ALL`
};
await send_quick_replies_msg(senderId, vitaminData, quickButtons);
} else if (nutrDataNeeded == "ALL") {
let allData = await totalSummary(foodToAnalyse);
await typingOnOff(senderId, 3);
await send_text_message(senderId, allData);
await typingOnOff(senderId, 3);
context = "";
await send_text_message(
senderId,
"Feel free to give me another photo/photo's URL or name of food ;)"
);
}
} else if (context == "If this is a label") {
let userAnswer = userInput.payload;
if (userAnswer != "LABEL:NO") {
let userLabel = userInput.payload.slice(6);
let quickButtons = {
Calories: `NUTRDATA#${userLabel}#CALORIES`,
"Proteins/Fats/Carbs": `NUTRDATA#${userLabel}#NUTRIENTS`,
Vitamins: `NUTRDATA#${userLabel}#VITAMINS`,
"All together": `NUTRDATA#${userLabel}#ALL`
};
await typingOnOff(senderId, 3);
context = "What data to display";
await send_quick_replies_msg(
senderId,
`What nutrient data for ${userLabel} are you interested in?`,
quickButtons
);
} else {
await typingOnOff(senderId, 3);
context = "";
await send_text_message(
senderId,
"Ok. Feel free to give me another photo/photo's URL or name of food ;)"
);
}
}
// Getting started button was clicked
if (userInput.payload == "GETTING_STARTED") {
await send_text_message(
senderId,
"Hi! I'm a Fitmoh. I can analyse food's composition by image"
);
await typingOnOff(senderId, 4);
await send_text_message(
senderId,
"Give me an image of some food 🍕 🍔🍭 and I'll do my best to provide nutrient data for it (calories, proteins/fats/carbohydrates, vitamins content) 🔍 📊"
);
await typingOnOff(senderId, 3);
await send_text_message(
senderId,
"You can also drop me a link to a food image or simply type the name of the food."
);
}
// Persistent menu >> Help button was clicked
if (userInput.payload == "NEEDHELP") {
await typingOnOff(senderId, 3);
await send_text_message(
senderId,
"I'm a Fitmoh. Give me a photo of some food and I will do my best to:\n- guess what's on the photo and \n- tell you some useful info about the composition of this food (caloric value, proteins/fats/carbohydrates ratio, vitamins content) 🔍 📊"
);
await typingOnOff(senderId, 3);
await send_text_message(
senderId,
"Nutrients data: Nutritionix API (http://www.nutritionix.com/api)\nImage content analysis: Google Cloud Vision API (https://cloud.google.com/vision/)"
);
await typingOnOff(senderId, 3);
await send_share_button_msg(senderId);
await typingOnOff(senderId, 6);
await send_text_message(
senderId,
"Feel free to:\n- upload a photo of some food from your camera or photos;\n- drop me a link to a food image or\n- simply type a name of food 🍕 🍔🍭"
);
}
} catch (error) {
console.log(`\nError from buttonclick handling block: ${error}`);
await send_text_message(senderId, error);
await typingOnOff(senderId, 3);
await send_text_message(
senderId,
"Feel free to give me another photo of food/URL to a photo of food or just a name of food ;)"
);
}
// TEXT INPUT is handled here
} else if (userInput.type == "text") {
try {
if (context == "Awaiting user's label") {
// Any text input (including URL) will be considered as user's name for the food
let usersLabel = userInput.payload;
await typingOnOff(senderId, 3);
await send_text_message(
senderId,
`Okay, let me see what info I can find for ${usersLabel}..`
);
await typingOnOff(senderId, 3);
let quickButtons = {
Calories: `NUTRDATA#${usersLabel}#CALORIES`,
"Proteins/Fats/Carbs": `NUTRDATA#${usersLabel}#NUTRIENTS`,
Vitamins: `NUTRDATA#${usersLabel}#VITAMINS`,
"All together": `NUTRDATA#${usersLabel}#ALL`
};
await typingOnOff(senderId, 3);
context = "What data to display";
await send_quick_replies_msg(
senderId,
`What nutrient data for ${usersLabel} are you interested in?`,
quickButtons
);
} else {
// Here we may get either a name of food or an URL
let usersLabel = userInput.payload;
if (usersLabel.match(regex)) {
// User entered a string which qualifies as a valid URL
let imgLabels = await googleVisionUrl(usersLabel);
await send_text_message(senderId, "Analysing image by URL...");
await typingOnOff(senderId, 3);
await send_text_message(senderId, "Finished");
if (imgLabels.length > 0) {
await send_text_message(
senderId,
`My best guess that this image shows:\n\n${imgLabels[0].toUpperCase()}`
);
let quickButtons = {
Correct: `LABEL:${imgLabels[0]}`,
"My variant": `LABEL:USERDEFINES`
};
if (imgLabels.length > 1) {
for (let label of imgLabels.slice(1)) {
quickButtons[label] = `LABEL:${label}`;
}
}
await typingOnOff(senderId, 3);
await send_quick_replies_msg(
senderId,
"Is that right? Please confirm, choose another variant from my guesses or enter your own variant",
quickButtons
);
context = "User picks up a label";
} else {
// No labels were picked up
await send_text_message(
senderId,
"Unfortunately I failed to pick up any terms for the image by your link. Are you sure that this URL and/or image are Ok? Maybe try with a different one?"
);
}
} else {
// User entered some text which is supposed to be a food label
let quickButtons = {
Yes: `LABEL:${usersLabel}`,
No: "LABEL:NO"
};
context = "If this is a label";
await typingOnOff(senderId, 3);
await send_quick_replies_msg(
senderId,
`Should I consider "${usersLabel.toUpperCase()}" as the name of food for which I should search nutrient data?`,
quickButtons
);
}
}
} catch (error) {
console.log("Error from text handling block");
await send_text_message(senderId, error);
await typingOnOff(senderId, 3);
await send_text_message(
senderId,
"Feel free to give me another photo of food/URL to a photo of food or just a name of food ;)"
);
}
// OTHER INPUT (besides image upload, text input or quick reply buttons click) is handled here
} else if (userInput.type == "other") {
try {
await send_text_message(senderId, ";)");
await typingOnOff(senderId, 3);
await send_text_message(
senderId,
"Feel free to give me a photo of food/URL to a photo of food or just a name of food ;)"
);
} catch (error) {
console.log("Error from other-input-types handling block");
await send_text_message(senderId, error);
}
}
}
// ===================================================================================================================//
// === NUTRITIONIX (getting nutrient data) ===========================================================================//
// ===================================================================================================================//
async function getNutrients(food) {
// Makes a request to Nutritionix API and returns all nutrient data for a given food
try {
let response = await fetch(nutrietnsURL, {
method: "POST",
headers: {
"Content-Type": "application/json",
"x-app-id": process.env.nutritionixAppID || keys.nutritionixAppID,
"x-app-key": process.env.nutritionixAppKey || keys.nutritionixAppKey,
"x-remote-user-id": 0
},
body: JSON.stringify({ query: food })
});
if (response.status == 200) {
return {
status: "ok",
data: await response.json()
};
} else {
// such food was not found
throw new Error("I couldn't match any of your foods");
}
} catch (error) {
console.log(`\nERROR from function getNutrients():\n${error}`);
throw new Error("I couldn't match any of your foods");
}
}
// === Calories ======================================================================================================//
function getCalories(allNutrients) {
// Parses the allNutrients data (got using getNutrients()) and returns
// the following fields: kkcal, kj, serving type, serving weight, serving quantity
try {
if (allNutrients.status == "ok") {
let food, enercKCal, enercKj, servingQty, servingUnit, servingWeightGrams;
food = allNutrients.data.foods[0].food_name;
servingQty = allNutrients.data.foods[0].serving_qty;
servingUnit = allNutrients.data.foods[0].serving_unit;
servingWeightGrams = allNutrients.data.foods[0].serving_weight_grams;
let fullNutrients = allNutrients.data.foods[0].full_nutrients;
// attr_id 208 ENERC_KCAL Energy kcal
// attr_id 268 ENERC_KJ Energy kJ
for (let nutrient of fullNutrients) {
if (nutrient.attr_id == 208) {
enercKCal = nutrient.value;
} else if (nutrient.attr_id == 268) {
enercKj = nutrient.value;
}
}
if (!enercKj && enercKCal) {
enercKj = enercKCal * 4.184;
}
if (!enercKCal && enercKj) {
enercKCal = enercKj / 4.184;
}
enercKCal = Math.floor(enercKCal * 100) / 100;
enercKj = Math.floor(enercKj * 100) / 100;
return {
status: "ok",
data: {
food: food,
enercKCal: enercKCal,
enercKj: enercKj,
servingQty: servingQty,
servingUnit: servingUnit,
servingWeightGrams: servingWeightGrams
}
};
} else {
// network/db access error, product not found, product found but no info on calories etc
throw new Error(
"Sorry but I failed to find info about calorific value for the food you requested"
);
/*return {
"status": "not found",
"data": `Sorry but I failed to find info about calorific value of ${food}`
};*/
}
} catch (error) {
console.log(`\nERROR from function getCalories():\n${error}`);
throw new Error(
"Sorry but I failed to find info about calorific value for the food you requested"
);
}
}
function caloriesNumbersToText(caloriesData) {
// Using numbers for caloric content (got using getNutrients() >> getCalories()) composes a text summary
try {
if (caloriesData.status == "ok") {
let food, enercKCal100g, enercKj100g, kgToCoverDaylyEnergy, summary;
food = caloriesData.data.food;
enercKCal100g =
Math.floor(
((caloriesData.data.enercKCal * 100) /
caloriesData.data.servingWeightGrams) *
100
) / 100;
enercKj100g =
Math.floor(
((caloriesData.data.enercKj * 100) /
caloriesData.data.servingWeightGrams) *
100
) / 100;
kgToCoverDaylyEnergy = kgToCoverDailyNeeds(
averageDailyCalories,
enercKCal100g
);
summary = `${food.charAt(0).toUpperCase() +
food.slice(
1
)} contains approximately ${enercKCal100g} calories (${enercKj100g} kj) per 100 grams or ${
caloriesData.data.enercKCal
} calories (${caloriesData.data.enercKj} kj) per a standard serving (${
caloriesData.data.servingQty
} ${caloriesData.data.servingUnit}, ${
caloriesData.data.servingWeightGrams
} g).`;
summary += `\n\nSo an average person would have to consume ${kgToCoverDaylyEnergy} kg of ${food} to cover his/her daily energy requirements (~2200 kilocalories)`;
return {
status: "ok",
data: summary
};
} else {
throw new Error(
"Sorry but I failed to find info about calorific value for the food you requested"
);
}
} catch (error) {
console.log(`\nERROR from function caloriesNumbersToText():\n${error}`);
throw new Error(
"Sorry but I failed to find info about calorific value for the food you requested"
);
}
}
async function caloriesSummary(food) {
// Connects all functions to get a summary of caloric content for a given food
try {
let allNutrients = await getNutrients(food);
let caloriesData = await getCalories(allNutrients);
let calSummary = await caloriesNumbersToText(caloriesData);
if (calSummary.status == "ok") {
return calSummary.data;
}
} catch (error) {
console.log(`\nERROR from function caloriesSummary():\n${error}`);
throw new Error(
"Sorry but I failed to find info about calorific value for the food you requested"
);
}
}
// === Proteins/Fats/Carbohydrates % =================================================================================//
function getProtFatCarbs(allNutrients) {
// Parses the allNutrients data (got using getNutrients()) and returns
// the following fields: procnt, fat, chocdf, serving type, serving weight, serving quantity
// also calculates relative (%) content of proteins, fats and carbohydrates
try {
if (allNutrients.status == "ok") {
let food,
procnt,
fat,
chocdf,
procntRel,
fatRel,
chocdfRel,
servingQty,
servingUnit,
servingWeightGrams;
food = allNutrients.data.foods[0].food_name;
servingQty = allNutrients.data.foods[0].serving_qty;
servingUnit = allNutrients.data.foods[0].serving_unit;
servingWeightGrams = allNutrients.data.foods[0].serving_weight_grams;
let fullNutrients = allNutrients.data.foods[0].full_nutrients;
// attr_id 205 CHOCDF Carbohydrate, by difference g
// attr_id 204 FAT Total lipid (fat) g
// attr_id 203 PROCNT Protein g
for (let nutrient of fullNutrients) {
if (nutrient.attr_id == 203) {
procnt = nutrient.value;
} else if (nutrient.attr_id == 204) {
fat = nutrient.value;
} else if (nutrient.attr_id == 205) {
chocdf = nutrient.value;
}
}
// Let's calculate ratio of nutrients in terms of source of energy (1g prot or 1g of carbs = 4cal,
// 1g of fat = 9cal)
if (!procnt) {
procnt = 0;
}
if (!fat) {
fat = 0;
}
if (!chocdf) {
chocdf = 0;
}
let nutrSum =
procnt * protCalPerG + fat * fatCalPerG + chocdf * carbCalPerG;
procntRel =
Math.floor(((procnt * protCalPerG * 100) / nutrSum) * 100) / 100;
fatRel = Math.floor(((fat * fatCalPerG * 100) / nutrSum) * 100) / 100;
chocdfRel =
Math.floor(((chocdf * carbCalPerG * 100) / nutrSum) * 100) / 100;
return {
status: "ok",
data: {
food: food,
procnt: procnt,
fat: fat,
chocdf: chocdf,
procntRel: procntRel,
fatRel: fatRel,
chocdfRel: chocdfRel,
servingQty: servingQty,
servingUnit: servingUnit,
servingWeightGrams: servingWeightGrams
}
};
} else {
// network/db access error, product not found, product found but no info on calories etc
throw new Error(
"Sorry but I failed to find info about proteins/fats/carbohydrates content in the food you requested"
);
/*return {
"status": "not found",
"data": `Sorry but I failed to find info about calorific value of ${food}`
};*/
}
} catch (error) {
console.log(`\nERROR from function getProtFatCarbs():\n${error}`);
throw new Error(
"Sorry but I failed to find info about proteins/fats/carbohydrates content in the food you requested"
);
/*return {
"status": "error",
"data": error
}*/
}
}
function kgToCoverDailyNeeds(dailyNeed, in100Grams) {
// Calculate daily needs (kg) of a product with given content of some substance in 100g
let eatDailyKg, eatDailySummary;
if (in100Grams == 0) {
eatDailySummary = "infinite quantity of";
} else {
eatDailyKg = Math.round((dailyNeed / in100Grams) * 0.1 * 100) / 100;
if (eatDailyKg > 5) {
eatDailySummary = `${eatDailyKg} ;)`;
} else {
eatDailySummary = eatDailyKg;
}
}
return eatDailySummary;
}
function protFatCarbsNumbersToText(nutrData) {
// Using numbers for main nutrients content (got using getNutrients() >> getProtFatCarbs()) composes a text summary
try {
if (nutrData.status == "ok") {
let food,
protIn100g,
fatsIn100g,
carbsIn100g,
kgToCoverDaylyProt,
kgToCoverDaylyFats,
kgToCoverDaylyCarbs,
summary;
food = nutrData.data.food;
protIn100g =
Math.floor(
((nutrData.data.procnt * 100) / nutrData.data.servingWeightGrams) *
100
) / 100;
fatsIn100g =
Math.floor(
((nutrData.data.fat * 100) / nutrData.data.servingWeightGrams) * 100
) / 100;
carbsIn100g =
Math.floor(
((nutrData.data.chocdf * 100) / nutrData.data.servingWeightGrams) *
100
) / 100;
kgToCoverDaylyProt = kgToCoverDailyNeeds(proteinsDaily, protIn100g);
kgToCoverDaylyFats = kgToCoverDailyNeeds(fatsDaily, fatsIn100g);
kgToCoverDaylyCarbs = kgToCoverDailyNeeds(carbsDaily, carbsIn100g);
summary = `${food.charAt(0).toUpperCase() +
food.slice(
1
)} contains approximately (per 100 g):\n- proteins: ${protIn100g} g (will provide ${
nutrData.data.procntRel
}% of calories);\n- fats: ${fatsIn100g} g (${
nutrData.data.fatRel
}%);\n- carbohydrates: ${carbsIn100g} g (${nutrData.data.chocdfRel}%);`;
summary += `\n\nIf to assume that an average person daily needs ${proteinsDaily}/${fatsDaily}/${carbsDaily} grams of proteins, fats and carbohydrates respectively, then in order to cover daily requirements in\n- proteins: one would need to consume ${kgToCoverDaylyProt} kg of ${food},\n- fats: ${kgToCoverDaylyFats} kg of ${food} and\n- carbohydrates: ${kgToCoverDaylyCarbs} kg of ${food}, respectively.`;
return {
status: "ok",
data: summary
};
} else {
throw new Error(
"Sorry but I failed to find info about proteins/fats/carbohydrates content in the food you requested"
);
}
} catch (error) {
console.log(`\nERROR from function protFatCarbsNumbersToText():\n${error}`);
throw new Error(
"Sorry but I failed to find info about proteins/fats/carbohydrates content in the food you requested"
);
}
}
async function protFatsCarbsSummary(food) {
// Connects all functions to get a summary for proteins/fats/carbohydrates content in given food
try {
let allNutrients = await getNutrients(food);
let nutrData = await getProtFatCarbs(allNutrients);
let nutrSummary = await protFatCarbsNumbersToText(nutrData);
if (nutrSummary.status == "ok") {
return nutrSummary.data;
}
} catch (error) {
console.log(`\nERROR from function protFatsCarbsSummary():\n${error}`);
throw new Error(
"Sorry but I failed to find info about proteins/fats/carbohydrates content in the food you requested"
);
}
}
// === Vitamins ======================================================================================================//
function getVitamins(allNutrients) {
// Parses the allNutrients data (got using getNutrients()) and returns
// the following fields: procnt, fat, chocdf, serving type, serving weight, serving quantity
// also calculates relative (%) content of proteins, fats and carbohydrates
try {
if (allNutrients.status == "ok") {
let food,
servingQty,
servingUnit,
servingWeightGrams,
vitK_430,
vitE_573,
vitE_323,
vitD3_326,
vitD2_325,
vitD_328,
vitD_324,
vitC_401,
vitB6_415,
vitB12_578,
vitB12_418,
vitA_320,
vitA_318,
vitE_342,
vitE_343,
vitE_341,
vitB1_404,
vitB2_405,
vitA1_319,
vitB5_410;
food = allNutrients.data.foods[0].food_name;
servingQty = allNutrients.data.foods[0].serving_qty;
servingUnit = allNutrients.data.foods[0].serving_unit;
servingWeightGrams = allNutrients.data.foods[0].serving_weight_grams;
let fullNutrients = allNutrients.data.foods[0].full_nutrients;
/*
319 RETOL Retinol (A-1) µg
320 VITA_RAE Vitamin A, RAE µg
318 VITA_IU Vitamin A, IU IU
404 THIA Thiamin (B-1) mg
405 RIBF Riboflavin (B-2) mg
410 PANTAC Pantothenic acid (B-5) mg
415 VITB6A Vitamin B-6 mg
578 NULL Vitamin B-12, added µg
418 VITB12 Vitamin B-12 µg
401 VITC Vitamin C, total ascorbic acid mg
326 CHOCAL Vitamin D3 (cholecalciferol) µg
325 ERGCAL Vitamin D2 (ergocalciferol) µg
328 VITD Vitamin D (D2 + D3) µg
324 VITD Vitamin D IU
573 NULL Vitamin E, added mg
323 TOCPHA Vitamin E (alpha-tocopherol) mg
342 TOCPHG Tocopherol, gamma (E) mg
343 TOCPHD Tocopherol, delta (E) mg
341 TOCPHB Tocopherol, beta (E) mg
430 VITK1 Vitamin K (phylloquinone) µg
*/
for (let nutrient of fullNutrients) {
if (nutrient.attr_id == 430) {
vitK_430 = nutrient.value;
} else if (nutrient.attr_id == 573) {
vitE_573 = nutrient.value;
} else if (nutrient.attr_id == 323) {
vitE_323 = nutrient.value;
} else if (nutrient.attr_id == 326) {
vitD3_326 = nutrient.value;
} else if (nutrient.attr_id == 325) {
vitD2_325 = nutrient.value;
} else if (nutrient.attr_id == 328) {
vitD_328 = nutrient.value;
} else if (nutrient.attr_id == 324) {
vitD_324 = nutrient.value;
} else if (nutrient.attr_id == 401) {
vitC_401 = nutrient.value;
} else if (nutrient.attr_id == 415) {
vitB6_415 = nutrient.value;
} else if (nutrient.attr_id == 578) {
vitB12_578 = nutrient.value;
} else if (nutrient.attr_id == 418) {
vitB12_418 = nutrient.value;
} else if (nutrient.attr_id == 320) {
vitA_320 = nutrient.value;
} else if (nutrient.attr_id == 318) {
vitA_318 = nutrient.value;
} else if (nutrient.attr_id == 342) {
vitE_342 = nutrient.value;
} else if (nutrient.attr_id == 343) {
vitE_343 = nutrient.value;
} else if (nutrient.attr_id == 341) {
vitE_341 = nutrient.value;
} else if (nutrient.attr_id == 404) {
vitB1_404 = nutrient.value;
} else if (nutrient.attr_id == 405) {
vitB2_405 = nutrient.value;
} else if (nutrient.attr_id == 319) {
vitA1_319 = nutrient.value;
} else if (nutrient.attr_id == 410) {
vitB5_410 = nutrient.value;
}
}
return {
status: "ok",
data: {
food: food,
servingQty: servingQty,
servingUnit: servingUnit,
servingWeightGrams: servingWeightGrams,
vitA_320: vitA_320,
vitA_318: vitA_318,
vitA1_319: vitA1_319,
vitB1_404: vitB1_404,
vitB2_405: vitB2_405,
vitB5_410: vitB5_410,
vitB6_415: vitB6_415,
vitB12_578: vitB12_578,
vitB12_418: vitB12_418,
vitC_401: vitC_401,
vitD3_326: vitD3_326,
vitD2_325: vitD2_325,
vitD_328: vitD_328,
vitD_324: vitD_324,
vitE_573: vitE_573,
vitE_323: vitE_323,
vitE_342: vitE_342,
vitE_343: vitE_343,
vitE_341: vitE_341,
vitK_430: vitK_430
}
};
} else {
// network/db access error, product not found, product found but no info on calories etc
throw new Error(
"Sorry but I failed to find info about vitamins content in the food you requested"
);
/*return {
"status": "not found",
"data": `Sorry but I failed to find info about calorific value of ${food}`
};*/
}
} catch (error) {
console.log(`\nERROR from function getVitamins():\n${error}`);
throw new Error(
"Sorry but I failed to find info about vitamins content in the food you requested"
);
/*return {
"status": "error",
"data": error
}*/
}
}
function vitaminNumbersToText(vitaminData) {
// Using numbers for main nutrients content (got using getNutrients() >> getProtFatCarbs()) composes a text summary
// P.s. % from daily requirements can be calculated but can be added later
try {
if (vitaminData.status == "ok") {
let food,
summary,
vitAmcg,
vitAME,
vitB1,
vitB2,
vitB5,
vitB6,
vitB12,
vitC,
vitDmcg,
vitDME,
vitE,
vitK;
let vitAmcgIn100g,
vitAMEIn100g,
vitB1In100g,
vitB2In100g,
vitB5In100g,
vitB6In100g,
vitB12In100g,
vitCIn100g,