Compare commits
65 Commits
galleryApi
...
master
Author | SHA1 | Date |
---|---|---|
|
75656c8f17 | |
![]() |
0d4323df9e | |
![]() |
5da7710af1 | |
|
76e503c4a9 | |
![]() |
59bcdcc3e8 | |
|
91b73215be | |
|
40eda82022 | |
|
2150d52b9d | |
|
fb21f179e6 | |
|
5777ee5131 | |
|
f96a50b7f4 | |
|
3f944eb49e | |
|
ab74529965 | |
|
73b3d67508 | |
|
1706a910fd | |
|
f922617e57 | |
![]() |
d18f173ef6 | |
|
b7bc87908e | |
![]() |
10a797d450 | |
|
23e5b2e329 | |
![]() |
3a64479fd4 | |
|
571a079622 | |
![]() |
d4d2a32a71 | |
|
2d71ff105d | |
![]() |
e8c29025aa | |
|
6b1cad684d | |
![]() |
b909a85225 | |
|
d2db8ead08 | |
![]() |
b69bc6200f | |
|
1cf66178ae | |
![]() |
6d03408495 | |
|
34e71a7dcf | |
![]() |
552cfbe574 | |
|
abcfc2dbca | |
![]() |
ed657df69a | |
|
b77e3692d2 | |
![]() |
3b75e915e3 | |
![]() |
02cc60f824 | |
![]() |
c2ee394195 | |
|
7db4089223 | |
|
e589d66e36 | |
|
cfa16dbdc7 | |
|
fe72636dd7 | |
|
f5d6c3cedc | |
|
136286599f | |
|
40c650f7d4 | |
|
b44c72e690 | |
|
4acaac5b84 | |
![]() |
8f2f36bce0 | |
|
22c2affa00 | |
![]() |
d38702698a | |
![]() |
7dda27e86e | |
|
0296de1703 | |
|
9384390811 | |
|
92974caef1 | |
|
956d0a72bd | |
|
c67378c3f4 | |
|
e34abbb017 | |
|
a4e9e9cfb3 | |
|
4d9a785812 | |
|
f68b1e78e0 | |
|
87afa13a42 | |
![]() |
4d251402af | |
![]() |
d96461aedb | |
![]() |
b7b168b2d0 |
|
@ -1,4 +0,0 @@
|
|||
#!/bin/sh
|
||||
. "$(dirname "$0")/_/husky.sh"
|
||||
|
||||
yarn install
|
|
@ -1,4 +0,0 @@
|
|||
#!/bin/sh
|
||||
. "$(dirname "$0")/_/husky.sh"
|
||||
|
||||
git status
|
|
@ -1,4 +0,0 @@
|
|||
#!/bin/sh
|
||||
. "$(dirname "$0")/_/husky.sh"
|
||||
|
||||
yarn lint-staged
|
33
Dockerfile
33
Dockerfile
|
@ -1,21 +1,26 @@
|
|||
ARG NODE_VERSION=18
|
||||
# Use an official Node.js runtime as a parent image
|
||||
FROM node:20-alpine
|
||||
|
||||
FROM node:${NODE_VERSION}-alpine
|
||||
# Set the working directory inside the container
|
||||
WORKDIR /app
|
||||
|
||||
ENV NODE_ENV production
|
||||
# Copy package files and set ownership
|
||||
COPY --chown=node:node package*.json ./
|
||||
|
||||
RUN mkdir -p /usr/src/iimtt_api && chown -R node:node /usr/src/iimtt_api
|
||||
|
||||
WORKDIR /usr/src/iimtt_api
|
||||
|
||||
COPY package.json yarn.lock ./
|
||||
|
||||
USER node
|
||||
|
||||
RUN yarn install --pure-lockfile
|
||||
# Install dependencies
|
||||
RUN npm install --omit=dev
|
||||
|
||||
# Copy the rest of the app's source code with correct ownership
|
||||
COPY --chown=node:node . .
|
||||
|
||||
EXPOSE 5174
|
||||
# Use a non-root user for better security
|
||||
USER node
|
||||
|
||||
CMD yarn start
|
||||
# Expose the application port
|
||||
EXPOSE 3000
|
||||
|
||||
# Set environment variables (optional)
|
||||
ENV NODE_ENV=production
|
||||
|
||||
# Start the application
|
||||
CMD ["npm", "run", "start"]
|
||||
|
|
|
@ -0,0 +1,22 @@
|
|||
/guided-tracing/A/
|
||||
|
||||
game_drawing /drawing/?id=
|
||||
game_drawing_v2 /drawing/v2/?id=
|
||||
game_drawing_v3 /drawing/v3/?id=
|
||||
drawing_phonics /drawing/drawing_phonics/?id=
|
||||
game_tick_variant1 /tick/v1/?id=
|
||||
game_tick_variant2 /tick/v2/?id=
|
||||
game_tick_varient3 /tick/v3/?id=
|
||||
game_cross_varient1 /cross/v1/?id=
|
||||
game_cross_varient2 /cross/v2/?id=
|
||||
game_cross_varient3 /cross/v3/?id=
|
||||
game_drag /drag/?id=
|
||||
game_drag_v2 /drag/v2/?id=
|
||||
game_drag_v3 /drag/v3/?id= // we do't use this version
|
||||
game_drag_v4 /drag/v4/?id=
|
||||
game_tick_v3_phonics /tick/tick_phonics_v1/?id=
|
||||
tick_phonics_option_6 /tick/tick_phonics_v2/?id=
|
||||
tick_phonics_option_9 /tick/tick_phonics_v3/?id=
|
||||
drag_drop_phonics /drag/dragdrop_phonics/?id=
|
||||
drag_phonics /drag/match_phonics/?id=
|
||||
cross_phonics_option_9 /cross/cross_phonics_v2/?id=
|
|
@ -27,6 +27,7 @@
|
|||
"install": "^0.13.0",
|
||||
"joi": "^17.3.0",
|
||||
"jsonwebtoken": "^8.5.1",
|
||||
"mariadb": "^3.4.0",
|
||||
"moment": "^2.24.0",
|
||||
"mongoose": "^8.7.1",
|
||||
"morgan": "^1.9.1",
|
||||
|
@ -56,7 +57,6 @@
|
|||
"eslint-plugin-prettier": "^3.1.1",
|
||||
"eslint-plugin-security": "^1.4.0",
|
||||
"faker": "^5.1.0",
|
||||
"husky": "7.0.4",
|
||||
"jest": "^26.0.1",
|
||||
"lint-staged": "^11.0.0",
|
||||
"node-mocks-http": "^1.8.0",
|
||||
|
@ -1735,6 +1735,12 @@
|
|||
"@babel/types": "^7.20.7"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/geojson": {
|
||||
"version": "7946.0.15",
|
||||
"resolved": "https://registry.npmjs.org/@types/geojson/-/geojson-7946.0.15.tgz",
|
||||
"integrity": "sha512-9oSxFzDCT2Rj6DfcHF8G++jxBKS7mBqXl5xrRW+Kbvjry6Uduya2iiwqHPhVXpasAVMBYKkEPGgKhd3+/HZ6xA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/graceful-fs": {
|
||||
"version": "4.1.9",
|
||||
"resolved": "https://registry.npmjs.org/@types/graceful-fs/-/graceful-fs-4.1.9.tgz",
|
||||
|
@ -1789,7 +1795,6 @@
|
|||
"version": "22.10.2",
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.10.2.tgz",
|
||||
"integrity": "sha512-Xxr6BBRCAOQixvonOye19wnzyDiUtTeqldOOmj3CkeblonbccA12PFwlufvRdrpjXxqnmUaeiU5EOA+7s5diUQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"undici-types": "~6.20.0"
|
||||
|
@ -6177,22 +6182,6 @@
|
|||
"node": ">=8.12.0"
|
||||
}
|
||||
},
|
||||
"node_modules/husky": {
|
||||
"version": "7.0.4",
|
||||
"resolved": "https://registry.npmjs.org/husky/-/husky-7.0.4.tgz",
|
||||
"integrity": "sha512-vbaCKN2QLtP/vD4yvs6iz6hBEo6wkSzs8HpRah1Z6aGmF2KW5PdYuAd7uX5a+OyBZHBhd+TFLqgjUgytQr4RvQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"bin": {
|
||||
"husky": "lib/bin.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/typicode"
|
||||
}
|
||||
},
|
||||
"node_modules/iconv-lite": {
|
||||
"version": "0.4.24",
|
||||
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz",
|
||||
|
@ -8464,6 +8453,40 @@
|
|||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/mariadb": {
|
||||
"version": "3.4.0",
|
||||
"resolved": "https://registry.npmjs.org/mariadb/-/mariadb-3.4.0.tgz",
|
||||
"integrity": "sha512-hdRPcAzs+MTxK5VG1thBW18gGTlw6yWBe9YnLB65GLo7q0fO5DWsgomIevV/pXSaWRmD3qi6ka4oSFRTExRiEQ==",
|
||||
"license": "LGPL-2.1-or-later",
|
||||
"dependencies": {
|
||||
"@types/geojson": "^7946.0.14",
|
||||
"@types/node": "^22.5.4",
|
||||
"denque": "^2.1.0",
|
||||
"iconv-lite": "^0.6.3",
|
||||
"lru-cache": "^10.3.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 14"
|
||||
}
|
||||
},
|
||||
"node_modules/mariadb/node_modules/iconv-lite": {
|
||||
"version": "0.6.3",
|
||||
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz",
|
||||
"integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"safer-buffer": ">= 2.1.2 < 3.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/mariadb/node_modules/lru-cache": {
|
||||
"version": "10.4.3",
|
||||
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz",
|
||||
"integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/math-intrinsics": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
|
||||
|
@ -15768,7 +15791,6 @@
|
|||
"version": "6.20.0",
|
||||
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.20.0.tgz",
|
||||
"integrity": "sha512-Ny6QZ2Nju20vw1SRHe3d9jVu6gJ+4e3+MMpqu7pqE5HT6WsTSlce++GQmK5UXS8mzV8DSYHrQH+Xrf2jVcuKNg==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/union-value": {
|
||||
|
|
|
@ -22,8 +22,7 @@
|
|||
"prettier:fix": "prettier --write **/*.js",
|
||||
"docker:prod": "docker-compose -f docker-compose.yml -f docker-compose.prod.yml up",
|
||||
"docker:dev": "docker-compose -f docker-compose.yml -f docker-compose.dev.yml up",
|
||||
"docker:test": "docker-compose -f docker-compose.yml -f docker-compose.test.yml up",
|
||||
"prepare": "husky install"
|
||||
"docker:test": "docker-compose -f docker-compose.yml -f docker-compose.test.yml up"
|
||||
},
|
||||
"keywords": [
|
||||
"node",
|
||||
|
@ -66,6 +65,7 @@
|
|||
"install": "^0.13.0",
|
||||
"joi": "^17.3.0",
|
||||
"jsonwebtoken": "^8.5.1",
|
||||
"mariadb": "^3.4.0",
|
||||
"moment": "^2.24.0",
|
||||
"mongoose": "^8.7.1",
|
||||
"morgan": "^1.9.1",
|
||||
|
@ -92,7 +92,6 @@
|
|||
"eslint-plugin-prettier": "^3.1.1",
|
||||
"eslint-plugin-security": "^1.4.0",
|
||||
"faker": "^5.1.0",
|
||||
"husky": "7.0.4",
|
||||
"jest": "^26.0.1",
|
||||
"lint-staged": "^11.0.0",
|
||||
"node-mocks-http": "^1.8.0",
|
||||
|
|
|
@ -2,12 +2,11 @@ const mongoose = require("mongoose");
|
|||
|
||||
const gameSchema = new mongoose.Schema({
|
||||
gameName: { type: String, required: true },
|
||||
userId: { type: String, required: true },
|
||||
childId: { type: String, required: true },
|
||||
gameID: { type: String, required: true },
|
||||
gameTime: { type: String, required: false },
|
||||
score: { type: String},
|
||||
gameStar: { type: Number},
|
||||
screenshotUrl: { type: String }, // Store the S3 URL of the screenshot
|
||||
});
|
||||
gameStar: { type: Number },
|
||||
screenshotUrl: { type: String },
|
||||
}, { collection: "gameData" });
|
||||
|
||||
module.exports = mongoose.model("Game", gameSchema);
|
||||
|
|
|
@ -2,7 +2,7 @@ const mongoose = require('mongoose');
|
|||
|
||||
// Define the GalleryImage schema
|
||||
const galleryImageSchema = new mongoose.Schema({
|
||||
userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true }, // Assuming you have a User model
|
||||
childId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true }, // Assuming you have a User model
|
||||
gameName: { type: String, required: true },
|
||||
gameID: { type: String, required: true },
|
||||
screenshotUrl: { type: String, required: true },
|
||||
|
|
|
@ -2,7 +2,7 @@ const mongoose = require("mongoose");
|
|||
|
||||
const galleryImageScema = new mongoose.Schema({
|
||||
gameName: { type: String, required: true },
|
||||
userId: { type: String, required: true },
|
||||
childId: { type: String, required: true },
|
||||
gameID: { type: String, required: true },
|
||||
screenshotUrl: { type: String },
|
||||
});
|
||||
|
|
|
@ -1,29 +1,27 @@
|
|||
const AWS = require('aws-sdk');
|
||||
const axios = require('axios');
|
||||
const mongoose = require('mongoose');
|
||||
const Game = require('../../models/gameModel'); // Ensure this path matches your project structure
|
||||
|
||||
const FormData = require('form-data');
|
||||
const Game = require('../../models/gameModel');
|
||||
const aiEvaluateImageToStar = async (req, res) => {
|
||||
try {
|
||||
const { userId, gameName, gameID, gameTime, gameStar, screenShot } = req.body;
|
||||
const { childId, gameName, gameID, gameTime, gameStar, screenShot } = req.body;
|
||||
if (!screenShot) {
|
||||
return res.status(400).json({ error: 'Screenshot is required' });
|
||||
}
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append('image', screenShot);
|
||||
const screenshotUrl = await axios.post('https://teachertrainingchennai.in/api/uploadBase64/', formData, {
|
||||
headers: {
|
||||
'Content-Type': 'multipart/form-data',
|
||||
},
|
||||
})
|
||||
// .then(response => {
|
||||
// console.log('Response:', response.data);
|
||||
// })
|
||||
// .catch(error => {
|
||||
// console.error('Error:', error);
|
||||
// });
|
||||
console.log(screenshotUrl.data.filePath)
|
||||
// Upload screenshot
|
||||
const formData = new FormData();
|
||||
formData.append('image', screenShot);
|
||||
|
||||
const screenshotUploadResponse = await axios.post('https://teachertrainingchennai.in/api/uploadBase64/', formData, {
|
||||
headers: {
|
||||
...formData.getHeaders(),
|
||||
},
|
||||
});
|
||||
|
||||
const screenshotUrl = screenshotUploadResponse.data.filePath;
|
||||
// The coloring was done by a 5-year-old kid. Give a score between 1 to 10 in JSON format.
|
||||
const openAiPayload = {
|
||||
model: 'gpt-4o-mini',
|
||||
messages: [
|
||||
|
@ -32,12 +30,12 @@ const aiEvaluateImageToStar = async (req, res) => {
|
|||
content: [
|
||||
{
|
||||
type: 'text',
|
||||
text: 'The coloring was done by a 5-year-old kid. Give a score between 1 to 10 in JSON format.',
|
||||
text: 'The coloring was done by a 5-year-old kid. Give a score between 1 to 10 the Respond ONLY with a valid JSON object like {"score": 7}. No extra text, no formatting, just raw JSON.',
|
||||
},
|
||||
{
|
||||
type: 'image_url',
|
||||
image_url: {
|
||||
url: screenshotUrl.data.filePath,
|
||||
url: screenshotUrl,
|
||||
},
|
||||
},
|
||||
],
|
||||
|
@ -46,7 +44,6 @@ const aiEvaluateImageToStar = async (req, res) => {
|
|||
max_tokens: 300,
|
||||
};
|
||||
|
||||
console.log('AAAAAA')
|
||||
const openAiResponse = await axios.post(
|
||||
'https://api.openai.com/v1/chat/completions',
|
||||
openAiPayload,
|
||||
|
@ -58,18 +55,27 @@ const aiEvaluateImageToStar = async (req, res) => {
|
|||
}
|
||||
);
|
||||
|
||||
// Extract the score from OpenAI's response
|
||||
const scoreResponse = openAiResponse.data.choices[0].message.content;
|
||||
const parsedScore = JSON.parse(scoreResponse);
|
||||
|
||||
console.log(openAiResponse)
|
||||
if (!openAiResponse.data.choices || openAiResponse.data.choices.length === 0) {
|
||||
throw new Error('Invalid OpenAI response format');
|
||||
}
|
||||
|
||||
let scoreResponse = openAiResponse.data.choices[0].message.content.trim();
|
||||
|
||||
if (scoreResponse.startsWith('```json')) {
|
||||
scoreResponse = scoreResponse.replace(/```json/, '').replace(/```/, '').trim();
|
||||
}
|
||||
|
||||
|
||||
const parsedScore = JSON.parse(scoreResponse);
|
||||
// console.log('Parsed Score:', parsedScore);
|
||||
|
||||
const gameData = new Game({
|
||||
gameName,
|
||||
userId,
|
||||
childId,
|
||||
gameID,
|
||||
gameTime,
|
||||
score: parsedScore.score || 'N/A', // Adjust key to match OpenAI response
|
||||
gameStar,
|
||||
gameStar: parsedScore.score || 'N/A',
|
||||
screenshotUrl,
|
||||
});
|
||||
|
||||
|
@ -81,7 +87,7 @@ console.log(openAiResponse)
|
|||
});
|
||||
} catch (error) {
|
||||
console.error('Error:', error.message);
|
||||
return res.status(500).json({ error: 'Something went wrong' });
|
||||
return res.status(500).json({ error: error.message || 'Something went wrong' });
|
||||
}
|
||||
};
|
||||
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
const aiFeedbackOnReport = async (req, res) => {
|
||||
const fetch = require('node-fetch');
|
||||
// const fetch = require('node-fetch');
|
||||
const url = process.env.AI_API_ENDOINT;
|
||||
const api_key = process.env.AI_API_KEY;
|
||||
const payload = {
|
||||
|
|
|
@ -1,11 +1,10 @@
|
|||
const aiFeedbackOnReport = async (req, res) => {
|
||||
// const fetch = require('node-fetch');
|
||||
const url = process.env.AI_API_ENDOINT;
|
||||
const api_key = process.env.AI_API_KEY;
|
||||
const api_key = process.env.OPENAI_KEY;
|
||||
const payload = {
|
||||
"model": "gpt-4o-mini",
|
||||
"messages": [{ "role": "user",
|
||||
"content": JSON.stringify(req.body.score) + " - is the students report card. " + req.body.instruction }]
|
||||
"messages": [{ "role": "user", "content": JSON.stringify(req.body.score) + " - is the students report card. " + req.body.instruction }]
|
||||
}
|
||||
try {
|
||||
const apiResponse = await fetch(url, {
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
const aiFollowupQuestion = async (req, res) => {
|
||||
|
||||
const { MongoClient } = require('mongodb');
|
||||
const fetch = require('node-fetch');
|
||||
// const fetch = require('node-fetch');
|
||||
const { v4: uuidv4 } = require('uuid');
|
||||
const url = process.env.MONGODB_URL;
|
||||
const dbName = process.env.MONGO_DB_NAME;
|
||||
|
@ -11,7 +11,7 @@ const aiFollowupQuestion = async (req, res) => {
|
|||
const database = client.db(dbName); // Replace with your database name
|
||||
const conversationsCollection = database.collection('conversations'); // Replace with your collection name
|
||||
|
||||
async function fetchOpenAICompletion(prompt, messages, model = "gpt-3.5-turbo-16k", max_tokens = 200) {
|
||||
async function fetchOpenAICompletion(prompt, messages, model = "gpt-3.5-turbo-16k", max_tokens = 600) {
|
||||
const response = await fetch('https://api.openai.com/v1/chat/completions', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
|
@ -26,12 +26,13 @@ const aiFollowupQuestion = async (req, res) => {
|
|||
});
|
||||
|
||||
const data = await response.json();
|
||||
return data.choices[0].message.content;
|
||||
return data;
|
||||
// return data.choices[0].message.content;
|
||||
}
|
||||
|
||||
|
||||
try {
|
||||
const { prompt, sessionId, model = "gpt-4o-mini", max_tokens = 200 } = req.body;
|
||||
const { prompt, sessionId, model = "gpt-4o-mini", max_tokens = 600 } = req.body;
|
||||
if (!conversationsCollection) {
|
||||
return res.status(500).json({
|
||||
success: false,
|
||||
|
@ -48,9 +49,10 @@ const aiFollowupQuestion = async (req, res) => {
|
|||
conversationHistory: [
|
||||
{ role: 'system', content: 'You are a helpful assistant.' },
|
||||
// { role: 'user', content: prompt },
|
||||
{ role: 'user', content: req.body.score + " - is the students report card. " + req.body.instruction },
|
||||
{ role: 'user', content: JSON.stringify(req.body.score) + " - is the students report card. " + req.body.instruction },
|
||||
],
|
||||
};
|
||||
// console.log(req.body.score[0])
|
||||
await conversationsCollection.insertOne(conversation);
|
||||
} else {
|
||||
conversation = await conversationsCollection.findOne({ sessionId: sessionId });
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
const aiFollowupQuestion = async (req, res) => {
|
||||
|
||||
const { MongoClient } = require('mongodb');
|
||||
const fetch = require('node-fetch');
|
||||
// const fetch = require('node-fetch');
|
||||
const { v4: uuidv4 } = require('uuid');
|
||||
const url = process.env.MONGODB_URL;
|
||||
const dbName = process.env.MONGO_DB_NAME;
|
||||
|
@ -21,11 +21,17 @@ const aiFollowupQuestion = async (req, res) => {
|
|||
body: JSON.stringify({
|
||||
model: model,
|
||||
messages: messages,
|
||||
// messages: [
|
||||
// { role: "system", content: "reply must not exceed 20 words" },
|
||||
// { role: "user", content: messages }
|
||||
// ],
|
||||
max_tokens: max_tokens,
|
||||
}),
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
// console.log(process.env.OPENAI_KEY)
|
||||
// console.log(data)
|
||||
return data;
|
||||
}
|
||||
|
||||
|
@ -46,7 +52,7 @@ const aiFollowupQuestion = async (req, res) => {
|
|||
conversation = {
|
||||
sessionId: newSessionId,
|
||||
conversationHistory: [
|
||||
{ role: 'system', content: 'answer within 50 words' },
|
||||
{ role: 'system', content: 'Reply to the questions asked by a kindergarten child, Sound excited to answer and encourage the child to ask more questions in 30 words' },
|
||||
{ role: 'user', content: prompt },
|
||||
],
|
||||
};
|
||||
|
|
|
@ -2,7 +2,7 @@ const aiMarkDrawing = async (req, res) => {
|
|||
|
||||
|
||||
const express = require('express');
|
||||
const fetch = require('node-fetch'); // For making HTTP requests
|
||||
// const fetch = require('node-fetch'); // For making HTTP requests
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
|
||||
|
|
|
@ -0,0 +1,166 @@
|
|||
const aiFollowupQuestion = async (req, res) => {
|
||||
const { MongoClient } = require('mongodb');
|
||||
// const fetch = require('node-fetch');
|
||||
const { v4: uuidv4 } = require('uuid');
|
||||
const url = process.env.MONGODB_URL;
|
||||
const dbName = process.env.MONGO_DB_NAME;
|
||||
const client = new MongoClient(url);
|
||||
|
||||
await client.connect();
|
||||
const database = client.db(dbName);
|
||||
const conversationsCollection = database.collection('conversations');
|
||||
|
||||
const MAX_TOKENS = 200;
|
||||
const PROVIDER_KEYS = JSON.parse(process.env.PROVIDER_KEY || '[]');
|
||||
|
||||
const PROVIDER_MODELS = {
|
||||
openai: [ "gpt-4o", "gpt-4o-mini", "o1", "o1-mini", "gpt-3.5-turbo", "gpt-3.5-turbo-mini", "gpt-3.5-mini", "gpt-3.5-turbo-2", "gpt-3.5-2", "gpt-3.5-turbo-2-mini", "gpt-3.5-2-mini" ],
|
||||
deepseek: [ "deepseek-chat", "deepseek-reasoner", "deepseek-qa", "deepseek-qa-mini" ],
|
||||
// Add more providers and models as needed
|
||||
};
|
||||
|
||||
async function fetchOpenAICompletion(messages, model, max_tokens = MAX_TOKENS) {
|
||||
// console.log(messages)
|
||||
const response = await fetch('https://api.openai.com/v1/chat/completions', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${process.env.OPENAI_KEY}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: model,
|
||||
messages: messages,
|
||||
max_tokens: max_tokens,
|
||||
}),
|
||||
});
|
||||
return response.json();
|
||||
}
|
||||
|
||||
async function fetchDeepSeekCompletion(messages, model) {
|
||||
const response = await fetch('https://api.deepseek.com/chat/completions', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${process.env.DEEPSEEK_KEY}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: model,
|
||||
messages: messages,
|
||||
stream: false,
|
||||
}),
|
||||
});
|
||||
return response.json();
|
||||
}
|
||||
|
||||
// Similar function for Gemini can be added here...
|
||||
|
||||
try {
|
||||
|
||||
const { prompt, sessionId, provider, model = "gpt-4o-mini", key, system } = req.body;
|
||||
|
||||
if (!key || !PROVIDER_KEYS.includes(key)) {
|
||||
return res.status(403).json({
|
||||
success: false,
|
||||
error: 'Unauthorized: Invalid or missing key.',
|
||||
});
|
||||
}
|
||||
|
||||
if (provider && req.body['list-models']) {
|
||||
if (PROVIDER_MODELS[provider]) {
|
||||
return res.json({
|
||||
success: true,
|
||||
models: PROVIDER_MODELS[provider],
|
||||
});
|
||||
} else {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error: 'Invalid provider specified.',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Check if the request is for listing AI providers
|
||||
if (req.body['list-ais']) {
|
||||
return res.json({
|
||||
success: true,
|
||||
providers: ['openai', 'deepseek', 'gemini', 'manual'],
|
||||
});
|
||||
}
|
||||
|
||||
if (!conversationsCollection) {
|
||||
return res.status(500).json({
|
||||
success: false,
|
||||
error: 'MongoDB is not connected yet. Please try again later.',
|
||||
});
|
||||
}
|
||||
|
||||
let conversation;
|
||||
|
||||
if (!sessionId) {
|
||||
const newSessionId = uuidv4();
|
||||
conversation = {
|
||||
sessionId: newSessionId,
|
||||
conversationHistory: [
|
||||
{ role: 'system', content: system },
|
||||
{ role: 'user', content: prompt },
|
||||
],
|
||||
};
|
||||
await conversationsCollection.insertOne(conversation);
|
||||
} else {
|
||||
conversation = await conversationsCollection.findOne({ sessionId: sessionId });
|
||||
if (!conversation) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error: 'Invalid session ID.',
|
||||
});
|
||||
}
|
||||
conversation.conversationHistory.push({ role: 'user', content: prompt });
|
||||
}
|
||||
|
||||
let aiResponse;
|
||||
|
||||
if(prompt.length > 3) {
|
||||
switch (provider) {
|
||||
case 'openai':
|
||||
aiResponse = await fetchOpenAICompletion([{ role: 'user', content: prompt }], model);
|
||||
// console.log(aiResponse)
|
||||
break;
|
||||
case 'deepseek':
|
||||
aiResponse = await fetchDeepSeekCompletion([{ role: 'user', content: prompt }], model);
|
||||
break;
|
||||
// case 'gemini':
|
||||
// aiResponse = await fetchGeminiCompletion(conversation.conversationHistory, model);
|
||||
// break;
|
||||
// Add more cases for other providers as needed
|
||||
default:
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error: 'Invalid provider specified.',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
conversation.conversationHistory.push({ role: 'assistant', content: aiResponse.choices ? aiResponse.choices[0].message.content : aiResponse.response });
|
||||
|
||||
await conversationsCollection.updateOne(
|
||||
{ sessionId: conversation.sessionId },
|
||||
{ $set: { conversationHistory: conversation.conversationHistory } }
|
||||
);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
data: aiResponse.choices ? aiResponse.choices[0].message.content : aiResponse.response,
|
||||
total_tokens: aiResponse.usage ? aiResponse.usage.total_tokens : undefined,
|
||||
sessionId: conversation.sessionId,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error generating response:', error.message);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
error: 'Something went wrong. Please try again later.',
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = aiFollowupQuestion;
|
|
@ -3,7 +3,7 @@ const GalleryImage = require('../../models/getGalleyImage');
|
|||
const getGalleryImage = async (req, res) => {
|
||||
try {
|
||||
// Extract query parameters for filtering (if provided)
|
||||
const { gameName, userId, gameID} = req.query;
|
||||
const { gameName, childId, gameID} = req.query;
|
||||
|
||||
// Build a filter object based on the query parameters
|
||||
const filter = {};
|
||||
|
@ -12,15 +12,15 @@ const getGalleryImage = async (req, res) => {
|
|||
filter.gameName = gameName;
|
||||
}
|
||||
|
||||
if (userId) {
|
||||
filter.userId = userId;
|
||||
if (childId) {
|
||||
filter.childId = childId;
|
||||
}
|
||||
if (gameID) {
|
||||
filter.gameID = gameID;
|
||||
}
|
||||
|
||||
// Fetch gallery images with filters and selected fields
|
||||
const galleryImages = await GalleryImage.find(filter).select('gameName userId gameID screenshotUrl'); // Select only these fields
|
||||
const galleryImages = await GalleryImage.find(filter).select('gameName childId gameID screenshotUrl'); // Select only these fields
|
||||
|
||||
if (!galleryImages.length) {
|
||||
return res.status(404).json({ message: 'No images found' });
|
||||
|
|
|
@ -0,0 +1,147 @@
|
|||
require("dotenv").config();
|
||||
const express = require("express");
|
||||
const mariadb = require("mariadb");
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
// Create MariaDB connection pool
|
||||
const pool = mariadb.createPool({
|
||||
host: process.env.MARIA_HOST,
|
||||
user: process.env.MARIA_USER,
|
||||
password: process.env.MARIA_PASS,
|
||||
database: process.env.MARIA_DBNM,
|
||||
connectionLimit: 5
|
||||
});
|
||||
|
||||
const getGameData = async (req, res) => {
|
||||
let conn;
|
||||
let items = 'ws2gamelink';
|
||||
try {
|
||||
const { wsname } = req.query;
|
||||
if (!items || !wsname) {
|
||||
return res.status(400).json({ error: "Missing items or wsname parameter" });
|
||||
}
|
||||
|
||||
console.log("Fetching game data from table:", items);
|
||||
|
||||
conn = await pool.getConnection();
|
||||
|
||||
// Fetching the first dataset
|
||||
const ws2gamelinkQuery = `SELECT * FROM \`${items}\` WHERE wsname = ?`;
|
||||
const rows = await conn.query(ws2gamelinkQuery, [wsname]);
|
||||
|
||||
if (!rows.length) {
|
||||
return res.status(404).json({ error: "No data found" });
|
||||
}
|
||||
|
||||
let gamelinkArray = rows[0].gamelink;
|
||||
|
||||
// Ensure gamelinkArray is an array
|
||||
if (typeof gamelinkArray === "string") {
|
||||
gamelinkArray = [gamelinkArray]; // Convert to array if it's a string
|
||||
}
|
||||
if (!Array.isArray(gamelinkArray)) {
|
||||
return res.status(500).json({ error: "Invalid gamelink data format" });
|
||||
}
|
||||
|
||||
const gameDataResults = [];
|
||||
|
||||
for (const link of gamelinkArray) {
|
||||
const gameLinkParts = link.split('/');
|
||||
let gameNameFromUrl = '';
|
||||
let gameIdData = '';
|
||||
let gameTableName = '';
|
||||
let gameVersion = '';
|
||||
|
||||
if (gameLinkParts.length === 5) {
|
||||
gameNameFromUrl = gameLinkParts[3];
|
||||
gameIdData = gameLinkParts[4].split('=')[1]; // Extracting ID
|
||||
} else if (gameLinkParts.length === 6) {
|
||||
gameNameFromUrl = gameLinkParts[3];
|
||||
gameVersion = gameLinkParts[4];
|
||||
gameIdData = gameLinkParts[5].split('=')[1]; // Extracting ID
|
||||
}
|
||||
|
||||
if (gameNameFromUrl === 'drawing' && gameVersion === 'v2') {
|
||||
gameTableName = 'game_drawing_v2';
|
||||
} else if (gameNameFromUrl === 'drawing' && gameVersion === 'v3') {
|
||||
gameTableName = 'game_drawing_v3';
|
||||
} else if (gameNameFromUrl === 'drawing' && gameVersion === 'drawing_writo') {
|
||||
gameTableName = 'drawing_writo';
|
||||
} else if (gameNameFromUrl === 'drawing' && gameVersion === 'drawing_phonics') {
|
||||
gameTableName = 'drawing_phonics';
|
||||
} else if (gameNameFromUrl === 'drawing') {
|
||||
gameTableName = 'game_drawing'; // General case, only if no version is specified
|
||||
} else if (gameNameFromUrl === 'drag' && gameVersion === 'v2') {
|
||||
gameTableName = 'game_drag_v2';
|
||||
} else if (gameNameFromUrl === 'drag' && gameVersion === 'v4') {
|
||||
gameTableName = 'game_drag_v4';
|
||||
} else if (gameNameFromUrl === 'drag' && gameVersion === 'dragdrop_phonics') {
|
||||
gameTableName = 'drag_drop_phonics';
|
||||
} else if (gameNameFromUrl === 'drag' && gameVersion === 'match_phonics') {
|
||||
gameTableName = 'drag_phonics';
|
||||
} else if (gameNameFromUrl === 'drag') {
|
||||
gameTableName = 'game_drag'; // General case for "drag"
|
||||
} else if (gameNameFromUrl === 'tick' && gameVersion === 'tick_phonics_v1') {
|
||||
gameTableName = 'tick_phonics_option_6';
|
||||
} else if (gameNameFromUrl === 'tick' && gameVersion === 'tick_phonics_v2') {
|
||||
gameTableName = 'tick_phonics_option_9';
|
||||
} else if (gameNameFromUrl === 'tick' && gameVersion === 'tick_phonics_v3') {
|
||||
gameTableName = 'game_tick_v3_phonics';
|
||||
} else if (gameNameFromUrl === 'tick' && gameVersion === 'v1') {
|
||||
gameTableName = 'game_tick_variant1';
|
||||
} else if (gameNameFromUrl === 'tick' && gameVersion === 'v2') {
|
||||
gameTableName = 'game_tick_variant2';
|
||||
} else if (gameNameFromUrl === 'tick' && gameVersion === 'v3') {
|
||||
gameTableName = 'game_tick_varient3';
|
||||
} else if (gameNameFromUrl === 'cross' && gameVersion === 'cross_phonics_v1') {
|
||||
gameTableName = 'cross_phonics_option_6';
|
||||
} else if (gameNameFromUrl === 'cross' && gameVersion === 'cross_phonics_v2') {
|
||||
gameTableName = 'cross_phonics_option_9';
|
||||
} else if (gameNameFromUrl === 'cross' && gameVersion === 'v1') {
|
||||
gameTableName = 'game_cross_varient1';
|
||||
} else if (gameNameFromUrl === 'cross' && gameVersion === 'v2') {
|
||||
gameTableName = 'game_cross_varient2';
|
||||
} else if (gameNameFromUrl === 'cross' && gameVersion === 'v3') {
|
||||
gameTableName = 'game_cross_varient3';
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
// else if (gameNameFromUrl === 'cross' && gameVersion === 'v2') {
|
||||
// gameTableName = 'game_cross_varient2';
|
||||
// }
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
// console.log('Game Info:', { gameTableName, gameVersion, gameIdData });
|
||||
|
||||
if (gameTableName && gameIdData) {
|
||||
let gameConn;
|
||||
try {
|
||||
gameConn = await pool.getConnection();
|
||||
const gameDataQuery = `SELECT * FROM \`${gameTableName}\` WHERE id = ?`;
|
||||
const gameDataRows = await gameConn.query(gameDataQuery, [gameIdData]);
|
||||
gameDataResults.push({ link, data: gameDataRows });
|
||||
} catch (gameError) {
|
||||
console.error("Error fetching game data:", gameError);
|
||||
} finally {
|
||||
if (gameConn) gameConn.release();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
res.json({ wsData: rows, gameData: gameDataResults });
|
||||
} catch (err) {
|
||||
console.error("Database error:", err);
|
||||
res.status(500).json({ error: "Database error" });
|
||||
} finally {
|
||||
if (conn) conn.release();
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = getGameData;
|
|
@ -0,0 +1,136 @@
|
|||
const mariadb = require('mariadb');
|
||||
|
||||
const gameInfo = async (req, res) => {
|
||||
|
||||
// Create a connection pool
|
||||
const pool = mariadb.createPool({
|
||||
host: process.env.MARIA_HOST,
|
||||
user: process.env.MARIA_USER,
|
||||
password: process.env.MARIA_PASS,
|
||||
database: process.env.MARIA_DBNM,
|
||||
connectionLimit: 5,
|
||||
});
|
||||
|
||||
const { schoolId, teacherId } = req.query;
|
||||
|
||||
if (!schoolId && !teacherId) {
|
||||
return res.status(400).send({ error: 'Either schoolId or teacherId is required in the query parameters.' });
|
||||
}
|
||||
|
||||
let connection;
|
||||
try {
|
||||
// Establish a connection to the database
|
||||
connection = await pool.getConnection();
|
||||
|
||||
let queryCondition;
|
||||
let queryValue;
|
||||
|
||||
// Determine the query condition based on the parameters provided
|
||||
if (schoolId) {
|
||||
queryCondition = 'schoolId = ?';
|
||||
queryValue = schoolId;
|
||||
} else {
|
||||
queryCondition = 'teacherId = ?';
|
||||
queryValue = teacherId;
|
||||
}
|
||||
|
||||
// Query both game1 and game2 tables
|
||||
const query1 = `SELECT * FROM game_drawing WHERE ${queryCondition}`;
|
||||
const query2 = `SELECT * FROM game_drawing_v2 WHERE ${queryCondition}`;
|
||||
const query3 = `SELECT * FROM game_drawing_v3 WHERE ${queryCondition}`;
|
||||
const query4 = `SELECT * FROM drawing_phonics WHERE ${queryCondition}`;
|
||||
const query5 = `SELECT * FROM game_tick_variant1 WHERE ${queryCondition}`;
|
||||
const query6 = `SELECT * FROM game_tick_variant2 WHERE ${queryCondition}`;
|
||||
const query7 = `SELECT * FROM game_tick_varient3 WHERE ${queryCondition}`;
|
||||
const query8 = `SELECT * FROM game_cross_varient1 WHERE ${queryCondition}`;
|
||||
const query9 = `SELECT * FROM game_cross_varient2 WHERE ${queryCondition}`;
|
||||
const query10 = `SELECT * FROM game_cross_varient3 WHERE ${queryCondition}`;
|
||||
const query11 = `SELECT * FROM game_drag WHERE ${queryCondition}`;
|
||||
const query12 = `SELECT * FROM game_drag_v2 WHERE ${queryCondition}`;
|
||||
const query13 = `SELECT * FROM game_drag_v4 WHERE ${queryCondition}`;
|
||||
const query14 = `SELECT * FROM game_tick_v3_phonics WHERE ${queryCondition}`;
|
||||
const query15 = `SELECT * FROM tick_phonics_option_6 WHERE ${queryCondition}`;
|
||||
const query16 = `SELECT * FROM tick_phonics_option_9 WHERE ${queryCondition}`;
|
||||
const query17 = `SELECT * FROM drag_drop_phonics WHERE ${queryCondition}`;
|
||||
const query18 = `SELECT * FROM drag_phonics WHERE ${queryCondition}`;
|
||||
const query19 = `SELECT * FROM cross_phonics_option_9 WHERE ${queryCondition}`;
|
||||
|
||||
const [game_drawing, game_drawing_v2, game_drawing_v3, drawing_phonics, game_tick_variant1, game_tick_variant2, game_tick_varient3, game_cross_varient1, game_cross_varient2, game_cross_varient3, game_drag, game_drag_v2, game_drag_v4, game_tick_v3_phonics, tick_phonics_option_6, tick_phonics_option_9, drag_drop_phonics, drag_phonics, cross_phonics_option_9 ] = await Promise.all([
|
||||
connection.query(query1, [queryValue]),
|
||||
connection.query(query2, [queryValue]),
|
||||
connection.query(query3, [queryValue]),
|
||||
connection.query(query4, [queryValue]),
|
||||
connection.query(query5, [queryValue]),
|
||||
connection.query(query6, [queryValue]),
|
||||
connection.query(query7, [queryValue]),
|
||||
connection.query(query8, [queryValue]),
|
||||
connection.query(query9, [queryValue]),
|
||||
connection.query(query10, [queryValue]),
|
||||
connection.query(query11, [queryValue]),
|
||||
connection.query(query12, [queryValue]),
|
||||
connection.query(query13, [queryValue]),
|
||||
connection.query(query14, [queryValue]),
|
||||
connection.query(query15, [queryValue]),
|
||||
connection.query(query16, [queryValue]),
|
||||
connection.query(query17, [queryValue]),
|
||||
connection.query(query18, [queryValue]),
|
||||
connection.query(query19, [queryValue])
|
||||
]);
|
||||
|
||||
// const domain = 'https://domain.com/gamelink/?id=';
|
||||
const domain = process.env.GAME_DOMAIN;
|
||||
|
||||
const formattedGame1 = game_drawing.map(game => ({ ...game, game_id: `game_drawing-${game.id}`, game_link: `${domain}/drawing/?id=${game.id}`, }));
|
||||
const formattedGame2 = game_drawing_v2.map(({ status, ...game }) => ({ ...game, game_id: `game_drawing_v2-${game.id}`, game_link: `${domain}/drawing/v2/?id=${game.id}`, }));
|
||||
const formattedGame3 = game_drawing_v3.map(({ status, ...game }) => ({ ...game, game_id: `game_drawing_v3-${game.id}`, game_link: `${domain}/drawing/v3/?id=${game.id}`, }));
|
||||
const formattedGame4 = drawing_phonics.map(({ status, ...game }) => ({ ...game, game_id: `drawing_phonics-${game.id}`, game_link: `${domain}/drawing/drawing_phonics/?id=${game.id}`, }));
|
||||
const formattedGame5 = game_tick_variant1.map(({ status, ...game }) => ({ ...game, game_id: `game_tick_variant1-${game.id}`, game_link: `${domain}/tick/v1/?id=${game.id}`, }));
|
||||
const formattedGame6 = game_tick_variant2.map(({ status, ...game }) => ({ ...game, game_id: `game_tick_variant2-${game.id}`, game_link: `${domain}/tick/v2/?id=${game.id}`, }));
|
||||
const formattedGame7 = game_tick_varient3.map(({ status, ...game }) => ({ ...game, game_id: `game_tick_varient3-${game.id}`, game_link: `${domain}/tick/v3/?id=${game.id}`, }));
|
||||
const formattedGame8 = game_cross_varient1.map(({ status, ...game }) => ({ ...game, game_id: `game_cross_varient1-${game.id}`, game_link: `${domain}/cross/v1/?id=${game.id}`, }));
|
||||
const formattedGame9 = game_cross_varient2.map(({ status, ...game }) => ({ ...game, game_id: `game_cross_varient2-${game.id}`, game_link: `${domain}/cross/v2/?id=${game.id}`, }));
|
||||
const formattedGame10 = game_cross_varient3.map(({ status, ...game }) => ({ ...game, game_id: `game_cross_varient3-${game.id}`, game_link: `${domain}/cross/v3/?id=${game.id}`, }));
|
||||
const formattedGame11 = game_drag.map(({ status, ...game }) => ({ ...game, game_id: `game_drag-${game.id}`, game_link: `${domain}/drag/?id=${game.id}`, }));
|
||||
const formattedGame12 = game_drag_v2.map(({ status, ...game }) => ({ ...game, game_id: `game_drag_v2-${game.id}`, game_link: `${domain}/drag/v2/?id=${game.id}`, }));
|
||||
const formattedGame13 = game_drag_v4.map(({ status, ...game }) => ({ ...game, game_id: `game_drag_v4-${game.id}`, game_link: `${domain}/drag/v4/?id=${game.id}`, }));
|
||||
const formattedGame14 = game_tick_v3_phonics.map(({ status, ...game }) => ({ ...game, game_id: `game_tick_v3_phonics-${game.id}`, game_link: `${domain}/tick/tick_phonics_v1/?id=${game.id}`, }));
|
||||
const formattedGame15 = tick_phonics_option_6.map(({ status, ...game }) => ({ ...game, game_id: `tick_phonics_option_6-${game.id}`, game_link: `${domain}/tick/tick_phonics_v2/?id=${game.id}`, }));
|
||||
const formattedGame16 = tick_phonics_option_9.map(({ status, ...game }) => ({ ...game, game_id: `tick_phonics_option_9-${game.id}`, game_link: `${domain}/tick/tick_phonics_v3/?id=${game.id}`, }));
|
||||
const formattedGame17 = drag_drop_phonics.map(({ status, ...game }) => ({ ...game, game_id: `drag_drop_phonics-${game.id}`, game_link: `${domain}/drag/dragdrop_phonics/?id=${game.id}`, }));
|
||||
const formattedGame18 = drag_phonics.map(({ status, ...game }) => ({ ...game, game_id: `drag_phonics-${game.id}`, game_link: `${domain}/drag/match_phonics/?id=${game.id}`, }));
|
||||
const formattedGame19 = cross_phonics_option_9.map(({ status, ...game }) => ({ ...game, game_id: `cross_phonics_option_9-${game.id}`, game_link: `${domain}/cross/cross_phonics_v2/?id=${game.id}`, }));
|
||||
|
||||
|
||||
const combinedResults = {
|
||||
game_drawing: formattedGame1,
|
||||
game_drawing_v2: formattedGame2,
|
||||
game_drawing_v3: formattedGame3,
|
||||
drawing_phonics: formattedGame4,
|
||||
game_tick_variant1: formattedGame5,
|
||||
game_tick_variant2: formattedGame6,
|
||||
game_tick_varient3: formattedGame7,
|
||||
game_cross_varient1: formattedGame8,
|
||||
game_cross_varient2: formattedGame9,
|
||||
game_cross_varient3: formattedGame10,
|
||||
game_drag: formattedGame11,
|
||||
game_drag_v2: formattedGame12,
|
||||
game_drag_v4: formattedGame13,
|
||||
game_tick_v3_phonics: formattedGame14,
|
||||
tick_phonics_option_6: formattedGame15,
|
||||
tick_phonics_option_9: formattedGame16,
|
||||
drag_drop_phonics: formattedGame17,
|
||||
drag_phonics: formattedGame18,
|
||||
cross_phonics_option_9: formattedGame19
|
||||
};
|
||||
|
||||
res.status(200).send(combinedResults);
|
||||
} catch (error) {
|
||||
console.error('Error querying game tables:', error);
|
||||
res.status(500).send({ error: 'An error occurred while fetching game data.' });
|
||||
} finally {
|
||||
// Release the connection back to the pool
|
||||
if (connection) connection.release();
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = gameInfo;
|
|
@ -15,15 +15,19 @@ async function main() {
|
|||
const collection = database.collection('gameData'); // Replace with your collection name
|
||||
|
||||
// Find a single document
|
||||
// const user = await collection.findOne({ userId: 'dsfdfgffgfgeg' });
|
||||
// const user = await collection.findOne({ childId: 'dsfdfgffgfgeg' });
|
||||
|
||||
const { userId, gameName, gameID } = req.body;
|
||||
const gameData = await collection.findOne({
|
||||
userId: userId,
|
||||
gameName: gameName,
|
||||
gameID: gameID
|
||||
});
|
||||
|
||||
const { childId, gameName, gameID } = req.body;
|
||||
const gameData = await collection.findOne(
|
||||
{
|
||||
childId: childId,
|
||||
gameName: gameName,
|
||||
gameID: gameID
|
||||
},{
|
||||
sort: {_id: -1}
|
||||
}
|
||||
);
|
||||
// console.log('gameData', gameData);
|
||||
if (gameData) {
|
||||
res.json({gameData});
|
||||
} else {
|
||||
|
|
|
@ -4,7 +4,7 @@ const FormData = require('form-data'); // Import form-data for Node.js
|
|||
|
||||
const saveGalleryImage = async (req, res) => {
|
||||
try {
|
||||
const { userId, gameName, gameID, screenShot } = req.body;
|
||||
const { childId, gameName, gameID, screenShot } = req.body;
|
||||
|
||||
// Validate base64 format
|
||||
const isValidBase64 = validateBase64(screenShot);
|
||||
|
@ -41,12 +41,13 @@ const saveGalleryImage = async (req, res) => {
|
|||
throw new Error('Image upload failed: ' + uploadResponse.statusText);
|
||||
}
|
||||
|
||||
|
||||
// Extract and store the uploaded image URL from the response
|
||||
const screenshotUrl = uploadResponse.data.urls[0];
|
||||
|
||||
// Create and save gallery image data
|
||||
const galleryImageData = new GalleryImage({
|
||||
userId,
|
||||
childId,
|
||||
gameName,
|
||||
gameID,
|
||||
screenshotUrl,
|
||||
|
|
|
@ -1,69 +0,0 @@
|
|||
var MongoClient = require('mongodb').MongoClient;
|
||||
const AWS = require('aws-sdk');
|
||||
|
||||
const saveGameScore = (req, res) => {
|
||||
const url = process.env.MONGODB_URL;
|
||||
const dbName = process.env.MONGO_DB_NAME;
|
||||
const client = new MongoClient(url, { useUnifiedTopology: true });
|
||||
client.connect((err) => {
|
||||
if (err) {
|
||||
console.error('Failed to connect to the server', err);
|
||||
return;
|
||||
}
|
||||
// console.log('Connected successfully to server');
|
||||
const db = client.db(dbName);
|
||||
const collection = db.collection('gameData');
|
||||
// const data = req.body;
|
||||
const { userId, gameName, gameID, gameTime, score,gameStar, screenShot } = req.body;
|
||||
const data = {
|
||||
userId: userId,
|
||||
gameName: gameName,
|
||||
gameID: gameID,
|
||||
gameTime: gameTime,
|
||||
score: score,
|
||||
gameStar:gameStar
|
||||
};
|
||||
|
||||
collection.insertOne(data, (err, result) => {
|
||||
if (err) {
|
||||
console.error('Failed to insert document', err);
|
||||
} else {
|
||||
// console.log('Document inserted with _id: ', result.insertedId);
|
||||
}
|
||||
client.close((err) => {
|
||||
if (err) {
|
||||
console.error('Failed to close connection', err);
|
||||
} else {
|
||||
// console.log('Connection closed');
|
||||
const s3 = new AWS.S3({
|
||||
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
|
||||
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
|
||||
region: process.env.AWS_REGION
|
||||
});
|
||||
if (screenShot != undefined) {
|
||||
// Upload image to S3
|
||||
let base64Image = screenShot.split(";base64,").pop();
|
||||
const buffer = Buffer.from(base64Image, 'base64');
|
||||
const s3Params = {
|
||||
Bucket: process.env.S3_BUCKET_NAME,
|
||||
Key: `images/${result.insertedId}.png`, // Change the file extension to .png
|
||||
Body: buffer,
|
||||
ContentEncoding: 'base64',
|
||||
ContentType: 'image/jpeg' // Change the content type to image/png
|
||||
};
|
||||
try {
|
||||
const data = s3.upload(s3Params).promise();
|
||||
console.log(`File uploaded successfully at ${data.Location}`);
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
}
|
||||
};
|
||||
res.send(result.insertedId);
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
module.exports = saveGameScore;
|
||||
|
|
@ -1,4 +1,5 @@
|
|||
const AWS = require("aws-sdk");
|
||||
const mongoose = require("mongoose");
|
||||
const Game = require("../../models/gameModel");
|
||||
|
||||
const s3 = new AWS.S3({
|
||||
|
@ -7,35 +8,55 @@ const s3 = new AWS.S3({
|
|||
region: process.env.AWS_REGION,
|
||||
});
|
||||
|
||||
// MongoDB Connection
|
||||
const mongoURI = process.env.MONGODB_URL;
|
||||
const dbName = process.env.MONGO_DB_NAME;
|
||||
|
||||
mongoose.connect(mongoURI, {
|
||||
dbName: dbName,
|
||||
useNewUrlParser: true,
|
||||
useUnifiedTopology: true,
|
||||
})
|
||||
.then(() =>
|
||||
console.log("Connected to MongoDB"))
|
||||
.catch((err) => console.error("MongoDB connection error:", err));
|
||||
|
||||
const saveGameScore2 = async (req, res) => {
|
||||
const { userId, gameName, gameID, gameTime, score, gameStar, screenShot } = req.body;
|
||||
const { childId, gameName, gameID, gameTime, score, gameStar, screenShot } = req.body;
|
||||
|
||||
try {
|
||||
if (!gameName || !userId || !gameID) {
|
||||
if (!gameName || !childId || !gameID) {
|
||||
return res.status(400).json({ error: "Missing required fields" });
|
||||
}
|
||||
|
||||
const newGame = new Game({
|
||||
gameName,
|
||||
userId,
|
||||
childId,
|
||||
gameID,
|
||||
gameTime,
|
||||
score,
|
||||
gameStar,
|
||||
});
|
||||
|
||||
// Save to MongoDB
|
||||
const result = await newGame.save();
|
||||
// Upload screenshot to S3 if provided
|
||||
if (screenShot) {
|
||||
let base64Image = screenShot.split(";base64,").pop();
|
||||
const buffer = Buffer.from(base64Image, 'base64');
|
||||
// const buffer = Buffer.from(screenShot, "base64");
|
||||
let base64Image = screenShot.split(";base64,").pop();
|
||||
const buffer = Buffer.from(base64Image, "base64");
|
||||
|
||||
const uploadParams = {
|
||||
Bucket: process.env.S3_BUCKET_NAME,
|
||||
Key: `images/${result._id}.png`,
|
||||
Body: buffer,
|
||||
ContentType: "image/png",
|
||||
};
|
||||
|
||||
const s3Response = await s3.upload(uploadParams).promise();
|
||||
newGame.screenshotUrl = s3Response.Location;
|
||||
await newGame.save();
|
||||
}
|
||||
|
||||
res.status(200).json({
|
||||
message: "Game data saved successfully",
|
||||
data: newGame,
|
||||
|
|
|
@ -22,7 +22,7 @@ const saveQuizResponse = require("../api/saveQuizResponse");
|
|||
const getGameScore = require("../api/getGameScore");
|
||||
const resultAfterQuizSubmit = require("../api/resultAfterQuizSubmit");
|
||||
const generateQuestions = require("../api/generateQuestions");
|
||||
const saveGameScore = require("../api/saveGameScore");
|
||||
// const saveGameScore = require("../api/saveGameScore");
|
||||
const saveGameScore2 = require("../api/saveGameScore2");
|
||||
const aiFeedbackOnReport = require("../api/aiFeedbackOnReport");
|
||||
const aiFeedbackActionParent = require("../api/aiFeedbackActionParent");
|
||||
|
@ -31,9 +31,11 @@ const aiMarkDrawing = require("../api/aiMarkDrawing");
|
|||
const aiFeedbackOnReportWithFollowup = require("../api/aiFeedbackOnReportWithFollowup");
|
||||
const aiTextToSpeech = require("../api/aiTextToSpeech");
|
||||
const aiEvaluateImageToStar = require("../api/aiEvaluateImageToStar");
|
||||
const getGameInfo = require("../api/getGameInfo");
|
||||
const saveGalleryImage = require("../api/saveGalleryImage");
|
||||
const getGalleryImage = require("../api/getGalleryImage");
|
||||
|
||||
const getGameData = require("../api/getGameData");
|
||||
// const aiTest = require("../api/aiTest");
|
||||
|
||||
|
||||
const router = express.Router();
|
||||
|
@ -149,9 +151,9 @@ router.get("/ping", (req, res) => {
|
|||
});
|
||||
|
||||
// For Quiz Result After Submit Quiz
|
||||
router.post("/saveGameScore", (req, res) => {
|
||||
saveGameScore(req, res);
|
||||
});
|
||||
// router.post("/saveGameScore", (req, res) => {
|
||||
// saveGameScore(req, res);
|
||||
// });
|
||||
|
||||
// For Quiz Result After Submit Quiz
|
||||
router.post("/saveGameScore2", (req, res) => {
|
||||
|
@ -193,8 +195,12 @@ router.get("/ping", (req, res) => {
|
|||
aiEvaluateImageToStar(req, res);
|
||||
});
|
||||
|
||||
|
||||
// Save Drawing Game Gallery Image
|
||||
// getGameInfo.
|
||||
router.get("/getGameInfo", (req, res) => {
|
||||
getGameInfo(req, res);
|
||||
});
|
||||
|
||||
// Save Drawing Game Gallery Image
|
||||
router.post("/saveGalleryImage", (req, res) => {
|
||||
saveGalleryImage(req, res);
|
||||
});
|
||||
|
@ -203,7 +209,15 @@ router.get("/ping", (req, res) => {
|
|||
router.get("/getGalleryImage", (req, res) => {
|
||||
getGalleryImage(req, res);
|
||||
});
|
||||
|
||||
|
||||
router.get("/getGameData", (req, res) => {
|
||||
getGameData(req, res);
|
||||
});
|
||||
|
||||
// Get Drawing Game Gallery Image
|
||||
// router.post("/aiTest", (req, res) => {
|
||||
// aiTest(req, res);
|
||||
// });
|
||||
|
||||
|
||||
module.exports = router;
|
||||
|
|
Loading…
Reference in New Issue