-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmain.js
More file actions
1366 lines (1245 loc) · 49.1 KB
/
main.js
File metadata and controls
1366 lines (1245 loc) · 49.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
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
import dotenv from 'dotenv';
import express from 'express';
import multer from 'multer';
import cors from 'cors';
import path from 'path';
import jwt from 'jsonwebtoken';
import bcrypt from 'bcryptjs';
import mysql from 'mysql2/promise';
import crypto from 'crypto';
import { GoogleGenAI, Type } from '@google/genai';
import { fileURLToPath } from 'url';
import { promises as fs } from 'fs';
dotenv.config();
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const uploadDir = path.resolve(process.cwd(), 'uploads');
fs.mkdir(uploadDir, { recursive: true }).catch(() => { });
const apiKeys = (process.env.GEMINI_API_KEYS || '')
.split(',')
.map((k) => k.trim())
.filter(Boolean);
const specialKey = process.env.SPECIAL_KEY ? process.env.SPECIAL_KEY.trim() : null;
const useVertexArg = process.argv.includes('--vertex');
const vertexApiKey = process.env.VERTEX_API_KEY;
let currentApiKeyIndex = 0;
function getNextApiKey() {
const apiKey = apiKeys[currentApiKeyIndex];
currentApiKeyIndex = (currentApiKeyIndex + 1) % apiKeys.length;
return apiKey;
}
const safetySettings = [
{ category: 'HARM_CATEGORY_HARASSMENT', threshold: 'BLOCK_NONE' },
{ category: 'HARM_CATEGORY_HATE_SPEECH', threshold: 'BLOCK_NONE' },
];
const nutritionResponseSchema = {
type: Type.OBJECT,
properties: {
"Nom de l'aliment": { type: Type.STRING },
'Poids (g)': { type: Type.STRING },
Ingredients: { type: Type.STRING },
Glucides: { type: Type.STRING },
Proteines: { type: Type.STRING },
Lipides: { type: Type.STRING },
Sauce: { type: Type.STRING },
Calories: { type: Type.STRING },
},
required: [
"Nom de l'aliment",
'Poids (g)',
'Calories',
'Glucides',
'Proteines',
'Lipides',
],
};
const chatResponseSchema = {
type: Type.ARRAY,
items: {
// Discriminated union by `type` to reduce hallucinated/irrelevant fields.
anyOf: [
{
type: Type.OBJECT,
properties: {
type: { type: Type.STRING, enum: ['message'] },
content: { type: Type.STRING },
},
required: ['type', 'content'],
additionalProperties: false,
},
{
type: Type.OBJECT,
properties: {
type: { type: Type.STRING, enum: ['quickReplies'] },
quickReplies: { type: Type.ARRAY, items: { type: Type.STRING } },
},
required: ['type', 'quickReplies'],
additionalProperties: false,
},
{
type: Type.OBJECT,
properties: {
type: { type: Type.STRING, enum: ['tip'] },
title: { type: Type.STRING },
description: { type: Type.STRING },
},
required: ['type', 'title', 'description'],
additionalProperties: false,
},
{
type: Type.OBJECT,
properties: {
type: { type: Type.STRING, enum: ['recipe'] },
title: { type: Type.STRING },
ingredients: { type: Type.ARRAY, items: { type: Type.STRING } },
instructions: { type: Type.ARRAY, items: { type: Type.STRING } },
calories: { type: Type.STRING },
carbs: { type: Type.STRING },
protein: { type: Type.STRING },
fat: { type: Type.STRING },
weight: { type: Type.STRING },
sourceUrl: { type: Type.STRING },
},
required: ['type', 'title', 'ingredients', 'instructions', 'calories'],
additionalProperties: false,
},
],
},
};
const generationDefaults = {
temperature: 0,
topP: 0.95,
topK: 1,
maxOutputTokens: 8192,
};
const normalizationInstruction = [
'You are a JSON post-processor. You will receive a nutrition JSON.',
'- First, verify the language of all human-readable string values.',
'- If any value is not English, translate ONLY the values into English.',
'- Preserve the exact JSON structure and keys. Do not rename keys.',
'- Keep all numbers and units as-is.',
'- If everything is already English, return the JSON unchanged.',
'- Respond with JSON only (no markdown, no code fences).',
].join('\n');
async function buildInlineImagePart(uploadedFile) {
if (!uploadedFile) {
return null;
}
if (uploadedFile.buffer && uploadedFile.buffer.length > 0) {
return {
inlineData: {
data: uploadedFile.buffer.toString('base64'),
mimeType: uploadedFile.mimetype || 'application/octet-stream',
},
};
}
const candidates = [];
if (uploadedFile.path) {
candidates.push(uploadedFile.path);
}
if (uploadedFile.destination && uploadedFile.filename) {
candidates.push(path.join(uploadedFile.destination, uploadedFile.filename));
}
if (uploadedFile.filename) {
candidates.push(path.join(uploadDir, uploadedFile.filename));
}
let absolutePath = null;
for (const candidate of candidates) {
if (!candidate) continue;
const resolved = path.isAbsolute(candidate) ? candidate : path.resolve(process.cwd(), candidate);
try {
await fs.access(resolved);
absolutePath = resolved;
break;
} catch (_) {
// try next candidate
}
}
if (absolutePath) {
try {
const buffer = await fs.readFile(absolutePath);
try {
await fs.unlink(absolutePath);
} catch (_) { }
return {
inlineData: {
data: buffer.toString('base64'),
mimeType: uploadedFile.mimetype || 'application/octet-stream',
},
};
} catch (readError) {
try {
console.warn('Failed to read uploaded image file:', readError?.message ?? readError);
} catch (_) { }
}
}
try {
console.warn('Uploaded image file not found on disk for inline upload.');
} catch (_) { }
return null;
}
function extractResponseText(response) {
if (!response) return '';
if (typeof response.text === 'string') return response.text;
if (typeof response.outputText === 'string') return response.outputText;
if (typeof response.output_text === 'string') return response.output_text;
if (Array.isArray(response.functionCalls) && response.functionCalls.length > 0) {
try {
return JSON.stringify(response.functionCalls[0]);
} catch (_) {
return '';
}
}
const candidateParts = response?.candidates?.[0]?.content?.parts;
if (Array.isArray(candidateParts)) {
for (const part of candidateParts) {
if (part?.jsonValue && typeof part.jsonValue === 'object') {
try {
return JSON.stringify(part.jsonValue);
} catch (_) {
// fall through to text handling
}
}
if (typeof part?.text === 'string' && part.text.trim()) {
return part.text;
}
if (part?.functionCall) {
try {
return JSON.stringify(part.functionCall);
} catch (_) {
// ignore parse issues
}
}
}
}
const contents = response?.contents;
if (Array.isArray(contents)) {
for (const content of contents) {
if (Array.isArray(content?.parts)) {
for (const part of content.parts) {
if (part?.jsonValue && typeof part.jsonValue === 'object') {
try {
return JSON.stringify(part.jsonValue);
} catch (_) {
// ignore
}
}
if (typeof part?.text === 'string' && part.text.trim()) {
return part.text;
}
}
}
}
}
return '';
}
function normalizeA2UIComponents(parsed, fallbackText = '') {
const toMessage = (content) => ([{ type: 'message', content: String(content || '').trim() }].filter(x => x.content));
if (Array.isArray(parsed)) {
const out = [];
for (const item of parsed) {
if (item && typeof item === 'object') {
if (typeof item.type === 'string' && item.type.trim()) {
out.push(item);
} else {
out.push({ type: 'message', content: JSON.stringify(item) });
}
} else if (typeof item === 'string' && item.trim()) {
out.push({ type: 'message', content: item });
}
}
return out.length ? out : toMessage(fallbackText);
}
if (parsed && typeof parsed === 'object') {
if (typeof parsed.type === 'string' && parsed.type.trim()) return [parsed];
return toMessage(fallbackText || JSON.stringify(parsed));
}
if (typeof parsed === 'string') return toMessage(parsed);
return toMessage(fallbackText);
}
function stripMarkdownFences(text) {
const t = String(text || '').trim();
if (!t) return '';
if (!t.startsWith('```')) return t;
return t.replace(/^```[a-zA-Z]*\s*/, '').replace(/\s*```$/, '').trim();
}
function tryParseJsonMaybe(text) {
const cleaned = stripMarkdownFences(text);
if (!cleaned) return null;
// First attempt
try {
const first = JSON.parse(cleaned);
// Some SDKs may wrap JSON as a string
if (typeof first === 'string') {
const inner = first.trim();
if ((inner.startsWith('[') && inner.endsWith(']')) || (inner.startsWith('{') && inner.endsWith('}'))) {
try {
return JSON.parse(inner);
} catch (_) {
return first;
}
}
}
return first;
} catch (_) {
// Heuristic: extract the outermost JSON array/object substring
const s = cleaned;
const firstArr = s.indexOf('[');
const lastArr = s.lastIndexOf(']');
if (firstArr >= 0 && lastArr > firstArr) {
const sub = s.slice(firstArr, lastArr + 1);
try { return JSON.parse(sub); } catch (_) {}
}
const firstObj = s.indexOf('{');
const lastObj = s.lastIndexOf('}');
if (firstObj >= 0 && lastObj > firstObj) {
const sub = s.slice(firstObj, lastObj + 1);
try { return JSON.parse(sub); } catch (_) {}
}
return null;
}
}
function sanitizeA2UIComponents(components) {
const out = [];
const pushMessage = (content) => {
const c = String(content || '').trim();
if (c) out.push({ type: 'message', content: c });
};
const toStringArray = (value) => {
if (!Array.isArray(value)) return [];
return value.map(v => String(v ?? '').trim()).filter(Boolean).slice(0, 12);
};
const toString = (value) => String(value ?? '').trim();
const items = Array.isArray(components) ? components : [];
for (const raw of items) {
if (!raw || typeof raw !== 'object') continue;
const type = toString(raw.type);
if (type === 'message') {
const content = toString(raw.content);
if (content) {
// If content itself looks like JSON, try to recover instead of showing raw JSON.
const maybe = tryParseJsonMaybe(content);
if (Array.isArray(maybe)) {
const recovered = sanitizeA2UIComponents(maybe);
if (recovered.length) {
out.push(...recovered);
continue;
}
}
pushMessage(content);
}
continue;
}
if (type === 'quickReplies') {
const quickReplies = toStringArray(raw.quickReplies);
if (quickReplies.length) out.push({ type: 'quickReplies', quickReplies });
continue;
}
if (type === 'tip') {
const title = toString(raw.title) || 'Tip';
const description = toString(raw.description);
if (description) out.push({ type: 'tip', title, description });
continue;
}
if (type === 'recipe') {
const title = toString(raw.title) || 'Recipe';
const ingredients = toStringArray(raw.ingredients);
const instructions = toStringArray(raw.instructions);
const calories = toString(raw.calories);
const carbs = toString(raw.carbs);
const protein = toString(raw.protein);
const fat = toString(raw.fat);
const weight = toString(raw.weight);
const sourceUrl = toString(raw.sourceUrl);
if (ingredients.length && instructions.length) {
out.push({
type: 'recipe',
title,
ingredients,
instructions,
calories,
carbs,
protein,
fat,
weight,
sourceUrl,
});
} else {
pushMessage(`I couldn't format a full recipe for "${title}". Try asking again with more specifics.`);
}
continue;
}
// Unknown type: reduce to a safe message.
try {
pushMessage(JSON.stringify(raw));
} catch (_) {
// ignore
}
}
return out.length ? out : [{ type: 'message', content: 'Sorry, I had trouble formatting that response. Please try again.' }];
}
async function englishNormalizeWithFlash(ai, originalJsonish) {
try {
const payload = typeof originalJsonish === 'string' ? originalJsonish : JSON.stringify(originalJsonish);
const response = await ai.models.generateContent({
model: 'gemini-2.5-flash',
contents: [
{
role: 'user',
parts: [
{
text: `Verify the following JSON is fully English. If not, translate values to English and return the JSON unchanged in structure and keys. Return JSON only.\n\nJSON:\n${payload}`,
},
],
},
],
systemInstruction: normalizationInstruction,
safetySettings,
config: {
...generationDefaults,
responseMimeType: 'application/json',
responseSchema: nutritionResponseSchema,
},
});
const text = extractResponseText(response).trim();
if (!text) return null;
const data = JSON.parse(text);
if (data && typeof data === 'object') {
return data;
}
return null;
} catch (e) {
try {
console.warn('englishNormalizeWithFlash failed:', e?.message ?? e);
} catch (_) { }
return null;
}
}
async function handleVertexRequest(req, res) {
if (!vertexApiKey) {
console.warn('Vertex mode requested but VERTEX_API_KEY not found.');
return handleRequestWithRetry(req, res);
}
// Temporarily enable Vertex mode for the SDK
process.env.GOOGLE_GENAI_USE_VERTEXAI = 'true';
const ai = new GoogleGenAI({ apiKey: vertexApiKey });
// Unset immediately to prevent polluting other requests/fallbacks
delete process.env.GOOGLE_GENAI_USE_VERTEXAI;
try {
const { file } = req;
const { message, lang } = req.body ?? {};
const acceptLangHeader = (req.get('accept-language') || '').split(',')[0].trim().toLowerCase();
const locale = (typeof lang === 'string' && lang.trim())
? lang.trim().toLowerCase()
: (acceptLangHeader || 'en');
const isEnglishLocale = (
(typeof lang === 'string' && lang.trim().toLowerCase().startsWith('en')) ||
(typeof acceptLangHeader === 'string' && acceptLangHeader.startsWith('en'))
);
const rawMessage = typeof message === 'string' ? message : '';
const trimmedMessage = rawMessage.trim();
if (!file && trimmedMessage.length === 0) {
return res.status(400).json({ ok: false, error: 'No input provided. Please include a message and/or an image.' });
}
let imagePart = null;
if (file) {
try {
imagePart = await buildInlineImagePart(file);
} catch (imageError) {
try {
console.warn('Vertex: Failed to prepare uploaded image:', imageError?.message ?? imageError);
} catch (_) { }
}
}
const parts = [];
if (imagePart) {
parts.push(imagePart);
}
if (rawMessage.length > 0 || parts.length === 0) {
parts.push({ text: rawMessage });
}
const userPrompt = rawMessage;
const systemInstructionText = [
'You cannot base yourself off typical serving sizes, only visual information and deep picture analysis of weight.',
'You must find the exact weight to the gram. Also remove ~10% of your estimated weight guess.',
'Always choose your minimum guess; if you estimate a range like 213-287, always pick the lowest number.',
`Reply in: ${locale === 'fr' ? 'french' : 'english'}.`,
].join(' ');
const systemInstruction = {
role: 'system',
parts: [{ text: systemInstructionText }],
};
try {
console.log('[Vertex AI] systemInstruction ->', systemInstructionText);
console.log('[Vertex AI] user prompt ->', userPrompt);
} catch (_) { }
const response = await ai.models.generateContent({
model: 'gemini-3-pro-preview',
contents: [
{
role: 'user',
parts,
},
],
systemInstruction,
safetySettings,
config: {
...generationDefaults,
responseMimeType: 'application/json',
responseSchema: nutritionResponseSchema,
},
});
let text = extractResponseText(response);
if (text && text.trim().startsWith('```')) {
text = text.replace(/^```[a-zA-Z]*\s*/, '').replace(/\s*```$/, '');
}
text = typeof text === 'string' ? text.trim() : '';
try {
console.log(`[Vertex AI][gemini-3-pro-preview] raw: ${text}`);
} catch (_) { }
let data = null;
if (text) {
try {
data = JSON.parse(text);
} catch (_) {
data = null;
}
}
if ((text && text.trim()) || (data && typeof data === 'object' && Object.keys(data).length > 0)) {
let finalPayload = (data && typeof data === 'object') ? data : text;
if (isEnglishLocale) {
try {
const normalized = await englishNormalizeWithFlash(ai, finalPayload);
if (normalized) {
finalPayload = normalized;
}
} catch (_) {
// keep original payload
}
}
await logRequestIp(req);
return res.json({ ok: true, data: finalPayload });
}
throw new Error('Vertex AI returned no content.');
} catch (error) {
console.warn('Vertex AI failed, reverting to standard API:', error?.message ?? error);
// Ensure Vertex mode is off for fallback
if (process.env.GOOGLE_GENAI_USE_VERTEXAI) delete process.env.GOOGLE_GENAI_USE_VERTEXAI;
return handleRequestWithRetry(req, res);
}
}
async function handleRequestWithRetry(req, res, attempt = 0) {
const keysToTry = [];
if (specialKey) keysToTry.push({ key: specialKey, isSpecial: true });
// Add normal keys, rotating starting from current index
for (let i = 0; i < apiKeys.length; i++) {
keysToTry.push({ key: apiKeys[(currentApiKeyIndex + i) % apiKeys.length], isSpecial: false });
}
// Advance rotation for next request
if (apiKeys.length > 0) {
currentApiKeyIndex = (currentApiKeyIndex + 1) % apiKeys.length;
}
if (keysToTry.length === 0) {
return res.status(503).json({ ok: false, error: 'Service is currently unavailable, please try again later.' });
}
// If we are in a recursive retry (attempt > 0), we might want to skip the special key if it was already tried?
// But handleRequestWithRetry is recursive with 'attempt' index.
// Let's just use the 'attempt' index to pick from our constructed list.
if (attempt >= keysToTry.length) {
return res.status(503).json({ ok: false, error: 'Service is currently unavailable, please try again later.' });
}
const { key: apiKey, isSpecial } = keysToTry[attempt];
const ai = new GoogleGenAI({ apiKey });
try {
const { file } = req;
const { message, lang } = req.body ?? {};
const acceptLangHeader = (req.get('accept-language') || '').split(',')[0].trim().toLowerCase();
const locale = (typeof lang === 'string' && lang.trim())
? lang.trim().toLowerCase()
: (acceptLangHeader || 'en');
const isEnglishLocale = (
(typeof lang === 'string' && lang.trim().toLowerCase().startsWith('en')) ||
(typeof acceptLangHeader === 'string' && acceptLangHeader.startsWith('en'))
);
const useFlash = String(req.query.flash || '0') === '1';
const rawMessage = typeof message === 'string' ? message : '';
const trimmedMessage = rawMessage.trim();
if (!file && trimmedMessage.length === 0) {
return res.status(400).json({ ok: false, error: 'No input provided. Please include a message and/or an image.' });
}
let imagePart = null;
if (file) {
try {
imagePart = await buildInlineImagePart(file);
} catch (imageError) {
try {
console.warn('Failed to prepare uploaded image:', imageError?.message ?? imageError);
} catch (_) { }
}
}
const parts = [];
if (imagePart) {
parts.push(imagePart);
}
if (rawMessage.length > 0 || parts.length === 0) {
parts.push({ text: rawMessage });
}
const userPrompt = rawMessage;
const contents = [
{
role: 'user',
parts,
},
];
const systemInstructionText = [
'You cannot base yourself off typical serving sizes, only visual information and deep picture analysis of weight.',
'You must find the exact weight to the gram. Also remove ~10% of your estimated weight guess.',
'Always choose your minimum guess; if you estimate a range like 213-287, always pick the lowest number.',
`Reply in: ${locale === 'fr' ? 'french' : 'english'}.`,
].join(' ');
const systemInstruction = {
role: 'system',
parts: [{ text: systemInstructionText }],
};
try {
console.log('[AI] systemInstruction ->', systemInstructionText);
console.log('[AI] user prompt ->', userPrompt);
} catch (_) { }
// Special key uses gemini-3-pro-preview, others use gemini-3-flash-preview (unless flash query param overrides)
let modelName = useFlash ? 'gemini-2.5-flash' : 'gemini-3-flash-preview';
if (isSpecial && !useFlash) {
modelName = 'gemini-3-pro-preview';
}
for (let i = 0; i < 10; i += 1) {
const response = await ai.models.generateContent({
model: modelName,
contents,
systemInstruction,
safetySettings,
config: {
...generationDefaults,
responseMimeType: 'application/json',
responseSchema: nutritionResponseSchema,
},
});
let text = extractResponseText(response);
if (text && text.trim().startsWith('```')) {
text = text.replace(/^```[a-zA-Z]*\s*/, '').replace(/\s*```$/, '');
}
text = typeof text === 'string' ? text.trim() : '';
try {
console.log(`[AI][${modelName}][try ${i + 1}/10] raw: ${text}`);
} catch (_) { }
let data = null;
if (text) {
try {
data = JSON.parse(text);
} catch (_) {
data = null;
}
}
if ((text && text.trim()) || (data && typeof data === 'object' && Object.keys(data).length > 0)) {
let finalPayload = (data && typeof data === 'object') ? data : text;
if (isEnglishLocale) {
try {
const normalized = await englishNormalizeWithFlash(ai, finalPayload);
if (normalized) {
finalPayload = normalized;
}
} catch (_) {
// keep original payload
}
}
await logRequestIp(req);
return res.json({ ok: true, data: finalPayload });
}
}
console.warn('Model returned no content after 10 tries');
// If we failed 10 times with this key/model, try next key
if (attempt + 1 < keysToTry.length) {
return handleRequestWithRetry(req, res, attempt + 1);
}
return res.status(503).json({ ok: false, error: 'Empty response from model after retries.' });
} catch (error) {
console.error(`Error with API key ${apiKey} (special=${isSpecial}):`, error);
const status = error?.status ?? error?.response?.status ?? 0;
// Retry on error if we have more keys
if (attempt + 1 < keysToTry.length) {
return handleRequestWithRetry(req, res, attempt + 1);
}
return res.status(503).json({ ok: false, error: 'Service is currently unavailable, please try again later.' });
}
}
const app = express();
const APP_TOKEN = process.env.APP_TOKEN || 'FromHectaroxWithLove';
const JWT_SECRET = process.env.JWT_SECRET || 'dev_secret';
const PORT = Number(process.env.PORT || 3000);
const ADMIN_USER = process.env.ADMIN_USER || 'admin';
const ADMIN_PASSWORD = process.env.ADMIN_PASSWORD || '';
const PASSWORD_AUTH = (() => {
const v = String(process.env.PASSWORD_AUTH ?? process.env.password_auth ?? 'true').toLowerCase();
return !(v === 'false' || v === '0' || v === 'off' || v === 'no');
})();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use('/static', express.static(path.join(__dirname, 'assets')));
function requireToken(req, res, next) {
const headerToken = req.get('x-app-token');
const bearer = req.get('authorization');
const bearerToken = bearer && /^Bearer\s+(.+)/i.test(bearer) ? bearer.replace(/^Bearer\s+/i, '') : undefined;
const token = headerToken || bearerToken;
if (token !== APP_TOKEN) {
return res.status(401).json({ ok: false, error: 'Unauthorized' });
}
return next();
}
app.use(cors());
// --------------------------
// Database bootstrap (MySQL)
// --------------------------
async function bootstrapDb() {
const { DB_HOST, DB_PORT, DB_USER, DB_PASSWORD, DB_NAME } = process.env;
const adminConn = await mysql.createConnection({
host: DB_HOST,
port: Number(DB_PORT || 3306),
user: DB_USER,
password: DB_PASSWORD,
multipleStatements: true,
});
await adminConn.query(`CREATE DATABASE IF NOT EXISTS \`${DB_NAME}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;`);
await adminConn.end();
const pool = await mysql.createPool({
host: DB_HOST,
port: Number(DB_PORT || 3306),
user: DB_USER,
password: DB_PASSWORD,
database: DB_NAME,
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0,
});
// Create tables if not exist
await pool.query(`
CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(191) NOT NULL UNIQUE,
password_hash VARCHAR(255) NOT NULL,
force_password_reset TINYINT(1) NOT NULL DEFAULT 1,
is_admin TINYINT(1) NOT NULL DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB;
`);
// Key-value settings storage for admin-configurable options
await pool.query(`
CREATE TABLE IF NOT EXISTS app_settings (
k VARCHAR(191) NOT NULL PRIMARY KEY,
v TEXT NULL,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB;
`);
// Logs of successful requests for reporting
await pool.query(`
CREATE TABLE IF NOT EXISTS request_logs (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
ip VARCHAR(64) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
INDEX idx_created_at (created_at),
INDEX idx_ip (ip)
) ENGINE=InnoDB;
`);
return pool;
}
let dbPoolPromise = bootstrapDb();
// --------------------------
// Helpers: client IP and logging
// --------------------------
function getClientIp(req) {
const xf = (req.get('x-forwarded-for') || '').split(',')[0].trim();
const ip = xf || req.ip || (req.socket && req.socket.remoteAddress) || '';
return String(ip).slice(0, 64);
}
async function logRequestIp(req) {
try {
const ip = getClientIp(req);
if (!ip) return;
const pool = await dbPoolPromise;
await pool.query('INSERT INTO request_logs (ip) VALUES (?)', [ip]);
} catch (e) {
try { console.warn('request ip log failed', e && e.message ? e.message : e); } catch (_) { }
}
}
// --------------------------
// Auth helpers
// --------------------------
function signToken(user) {
return jwt.sign({ sub: user.id, username: user.username, is_admin: !!user.is_admin }, JWT_SECRET, { expiresIn: '7d' });
}
function authJwt(req, res, next) {
const auth = req.get('authorization') || '';
const m = auth.match(/^Bearer\s+(.+)/i);
if (!m) return res.status(401).json({ ok: false, error: 'Missing token' });
try {
const payload = jwt.verify(m[1], JWT_SECRET);
req.user = payload;
next();
} catch (e) {
return res.status(401).json({ ok: false, error: 'Invalid token' });
}
}
// --------------------------
// Basic auth for Admin panel
// --------------------------
function parseBasicAuth(req) {
const header = req.get('authorization') || '';
if (!/^Basic\s+/i.test(header)) return null;
try {
const b64 = header.replace(/^Basic\s+/i, '');
const s = Buffer.from(b64, 'base64').toString('utf8');
const i = s.indexOf(':');
if (i < 0) return null;
return { user: s.slice(0, i), pass: s.slice(i + 1) };
} catch (_) { return null; }
}
function requireAdmin(req, res, next) {
if (!ADMIN_PASSWORD) {
return res.status(500).send('Admin password not set on server');
}
const creds = parseBasicAuth(req);
if (!creds || creds.user !== ADMIN_USER || creds.pass !== ADMIN_PASSWORD) {
res.set('WWW-Authenticate', 'Basic realm="NutriLens Admin"');
return res.status(401).send('Authentication required');
}
next();
}
// --------------------------
// Admin panel (simple HTML)
// --------------------------
app.get('/', requireAdmin, (req, res) => {
res.send(`<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>NutriLens Admin</title>
<style>
body{font-family:system-ui,-apple-system,Segoe UI,Roboto,Arial,sans-serif;margin:24px;}
form{margin:12px 0;padding:12px;border:1px solid #eee;border-radius:8px;max-width:520px}
input,button{padding:8px;margin:4px 0;font-size:14px}
.row{display:flex;gap:8px}
.row>*{flex:1}
code{background:#f6f8fa;padding:2px 6px;border-radius:4px}
.col{display:flex;gap:16px;align-items:flex-start}
.col>*{flex:1}
.help{color:#666;font-size:12px}
.preview{border:1px solid #eee;border-radius:8px;padding:12px;min-height:120px}
</style>
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
</head>
<body>
<h1>NutriLens Admin</h1>
<p>Invite a user: this creates a username with a temporary password. On first login, the user must set a new password.</p>
<form id="inviteForm">
<div class="row">
<input name="username" placeholder="username" required />
</div>
<button type="submit">Invite</button>
<div id="inviteOut"></div>
</form>
<h2>Announcement</h2>
<p class="help">Configure localized Markdown announcements shown in the app at startup. Users can choose "Hide forever" per-announcement; you can also provide separate messages for English and French.</p>
<form id="settingsForm">
<div class="row">
<input name="discord_url" placeholder="Discord invite URL (optional)" />
<input name="github_issues_url" placeholder="GitHub issues URL (optional)" />
</div>
<div class="col">
<div>
<h3>English</h3>
<textarea name="announcement_md_en" placeholder="English Markdown... Use $discord and $github_issues tokens to insert logos/links" rows="8"></textarea>
<h4>Preview (EN)</h4>
<div id="mdPreviewEn" class="preview"></div>
</div>
<div>
<h3>Français</h3>
<textarea name="announcement_md_fr" placeholder="Markdown français... Utilisez les tokens $discord et $github_issues" rows="8"></textarea>
<h4>Prévisualisation (FR)</h4>
<div id="mdPreviewFr" class="preview"></div>
</div>
</div>
<div class="row">
<button type="submit">Save</button>
<span id="saveOut"></span>
</div>
<div>
<h3>Tokens</h3>
<ul>
<li><code>$discord</code> → Discord logo + link (uses Discord URL)</li>
<li><code>$github_issues</code> → GitHub logo + link (uses GitHub Issues URL)</li>
</ul>
</div>
</form>
<h2>API</h2>
<p>Mobile login: <code>POST /auth/login { username, password }</code></p>
<p>Set password: <code>POST /auth/set-password (Bearer token) { newPassword }</code></p>
<p>Announcement: <code>GET /announcement</code> returns <code>{ ok, markdown }</code></p>
<h2>Reports</h2>
<p><a href="/admin/ip-report" download>Download IP report (last 24h)</a></p>
<script>
const form = document.getElementById('inviteForm');
form.addEventListener('submit', async (e) => {
e.preventDefault();
const fd = new FormData(form);
const username = fd.get('username');
const res = await fetch('/admin/invite', { method: 'POST', headers: { 'Content-Type':'application/json' }, body: JSON.stringify({ username }) });
const json = await res.json();
document.getElementById('inviteOut').textContent = JSON.stringify(json, null, 2);
});
// Settings form
const settingsForm = document.getElementById('settingsForm');
const mdEnEl = settingsForm.querySelector('textarea[name="announcement_md_en"]');
const mdFrEl = settingsForm.querySelector('textarea[name="announcement_md_fr"]');
const dUrlEl = settingsForm.querySelector('input[name="discord_url"]');
const gUrlEl = settingsForm.querySelector('input[name="github_issues_url"]');
const prevEnEl = document.getElementById('mdPreviewEn');
const prevFrEl = document.getElementById('mdPreviewFr');
const saveOut = document.getElementById('saveOut');
function tokenize(md) {