Compare commits
107 Commits
Author | SHA1 | Date |
---|---|---|
![]() |
3421a198f3 | |
|
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 | |
![]() |
5152ca2e23 | |
![]() |
4d251402af | |
![]() |
d96461aedb | |
![]() |
b7b168b2d0 | |
![]() |
e520169fb9 | |
|
ddc864a25d | |
|
9fa326666f | |
|
abcb44ace7 | |
|
8ecbe43e6e | |
|
583f85a7e8 | |
|
2dec203ad0 | |
|
9a64b60454 | |
|
2593bfc7d9 | |
|
3a73d0a9be | |
|
cad9154900 | |
|
c934f45726 | |
|
f1198c21de | |
|
8eb4da619a | |
|
b5d40f21a6 | |
|
411766987c | |
|
51c520108b | |
|
7fcc27ada1 | |
|
02ec79b262 | |
|
5e23f73645 | |
|
2cbf1ebbaa | |
|
5775c45d8c | |
|
0a78f89fa9 | |
|
101e1a2749 | |
|
7252cfcce4 | |
|
41c2ceb675 | |
|
da33f2ed43 | |
|
060e6b0f1a | |
|
58805dac6f | |
|
f490aac87e | |
|
67bc3e9995 | |
|
a9a0cd5ca3 | |
|
1244f5f06b | |
|
c74a6fd67d | |
![]() |
10b7fc5ee2 | |
|
879a792907 | |
|
554b4e8946 | |
|
0381f74f06 | |
|
8b420fb34f | |
|
f12e2d9e0a |
|
@ -1,3 +1,6 @@
|
||||||
node_modules
|
node_modules
|
||||||
.git
|
.git
|
||||||
.gitignore
|
.gitignore
|
||||||
|
**/docker-compose*
|
||||||
|
**/compose.y*ml
|
||||||
|
**/Dockerfile*
|
|
@ -3,7 +3,7 @@ node_modules
|
||||||
|
|
||||||
# yarn error logs
|
# yarn error logs
|
||||||
yarn-error.log
|
yarn-error.log
|
||||||
|
yarn.lock
|
||||||
# Environment varibales
|
# Environment varibales
|
||||||
.env*
|
.env*
|
||||||
!.env*.example
|
!.env*.example
|
||||||
|
|
|
@ -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
|
|
27
Dockerfile
27
Dockerfile
|
@ -1,15 +1,26 @@
|
||||||
FROM node:alpine
|
# Use an official Node.js runtime as a parent image
|
||||||
|
FROM node:20-alpine
|
||||||
|
|
||||||
RUN mkdir -p /usr/src/node-app && chown -R node:node /usr/src/node-app
|
# Set the working directory inside the container
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
WORKDIR /usr/src/node-app
|
# Copy package files and set ownership
|
||||||
|
COPY --chown=node:node package*.json ./
|
||||||
|
|
||||||
COPY package.json yarn.lock ./
|
# Install dependencies
|
||||||
|
RUN npm install --omit=dev
|
||||||
USER node
|
|
||||||
|
|
||||||
RUN yarn install --pure-lockfile
|
|
||||||
|
|
||||||
|
# Copy the rest of the app's source code with correct ownership
|
||||||
COPY --chown=node:node . .
|
COPY --chown=node:node . .
|
||||||
|
|
||||||
|
# Use a non-root user for better security
|
||||||
|
USER node
|
||||||
|
|
||||||
|
# Expose the application port
|
||||||
EXPOSE 3000
|
EXPOSE 3000
|
||||||
|
|
||||||
|
# Set environment variables (optional)
|
||||||
|
ENV NODE_ENV=production
|
||||||
|
|
||||||
|
# Start the application
|
||||||
|
CMD ["npm", "run", "start"]
|
||||||
|
|
|
@ -1,32 +1,31 @@
|
||||||
version: '3'
|
|
||||||
|
|
||||||
services:
|
services:
|
||||||
node-app:
|
iimtt_api:
|
||||||
build: .
|
build: .
|
||||||
image: node-app
|
image: iimtt_api
|
||||||
environment:
|
# environment:
|
||||||
- MONGODB_URL=mongodb://mongodb:27017/node-boilerplate
|
# - MONGODB_URL=mongodb://mongodb:27017/node-boilerplate
|
||||||
ports:
|
ports:
|
||||||
- '3000:3000'
|
- '5174:5174'
|
||||||
depends_on:
|
# depends_on:
|
||||||
- mongodb
|
# - mongodb
|
||||||
volumes:
|
volumes:
|
||||||
- .:/usr/src/node-app
|
- .:/usr/src/iimtt_api
|
||||||
networks:
|
# networks:
|
||||||
- node-network
|
# - host
|
||||||
|
# - node-network
|
||||||
|
|
||||||
mongodb:
|
# mongodb:
|
||||||
image: mongo:4.2.1-bionic
|
# image: mongo:4.2.1-bionic
|
||||||
ports:
|
# ports:
|
||||||
- '27017:27017'
|
# - '27017:27017'
|
||||||
volumes:
|
# volumes:
|
||||||
- dbdata:/data/db
|
# - dbdata:/data/db
|
||||||
networks:
|
# networks:
|
||||||
- node-network
|
# - node-network
|
||||||
|
|
||||||
volumes:
|
# volumes:
|
||||||
dbdata:
|
# dbdata:
|
||||||
|
|
||||||
networks:
|
# networks:
|
||||||
node-network:
|
# node-network:
|
||||||
driver: bridge
|
# driver: bridge
|
||||||
|
|
|
@ -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=
|
Binary file not shown.
File diff suppressed because it is too large
Load Diff
18
package.json
18
package.json
|
@ -1,6 +1,6 @@
|
||||||
{
|
{
|
||||||
"name": "iimttapi",
|
"name": "iimttapi",
|
||||||
"version": "0.0.1",
|
"version": "1.0.0",
|
||||||
"description": "Create a Node.js app for building production-ready RESTful APIs using Express, by running one command",
|
"description": "Create a Node.js app for building production-ready RESTful APIs using Express, by running one command",
|
||||||
"bin": "bin/createNodejsApp.js",
|
"bin": "bin/createNodejsApp.js",
|
||||||
"main": "src/index.js",
|
"main": "src/index.js",
|
||||||
|
@ -9,7 +9,8 @@
|
||||||
"node": ">=12.0.0"
|
"node": ">=12.0.0"
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"start": "pm2 start ecosystem.config.json --no-daemon",
|
"start": "NODE_ENV=production node src/index.js",
|
||||||
|
"start:pm2": "pm2 start ecosystem.config.json --no-daemon",
|
||||||
"dev": "cross-env NODE_ENV=development nodemon src/index.js",
|
"dev": "cross-env NODE_ENV=development nodemon src/index.js",
|
||||||
"test": "jest -i --colors --verbose --detectOpenHandles",
|
"test": "jest -i --colors --verbose --detectOpenHandles",
|
||||||
"test:watch": "jest -i --watchAll",
|
"test:watch": "jest -i --watchAll",
|
||||||
|
@ -21,8 +22,7 @@
|
||||||
"prettier:fix": "prettier --write **/*.js",
|
"prettier:fix": "prettier --write **/*.js",
|
||||||
"docker:prod": "docker-compose -f docker-compose.yml -f docker-compose.prod.yml up",
|
"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: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",
|
"docker:test": "docker-compose -f docker-compose.yml -f docker-compose.test.yml up"
|
||||||
"prepare": "husky install"
|
|
||||||
},
|
},
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"node",
|
"node",
|
||||||
|
@ -48,6 +48,7 @@
|
||||||
],
|
],
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"aws-sdk": "^2.1669.0",
|
"aws-sdk": "^2.1669.0",
|
||||||
|
"axios": "^1.7.7",
|
||||||
"bcryptjs": "^2.4.3",
|
"bcryptjs": "^2.4.3",
|
||||||
"body-parser": "^1.20.2",
|
"body-parser": "^1.20.2",
|
||||||
"compression": "^1.7.4",
|
"compression": "^1.7.4",
|
||||||
|
@ -57,15 +58,21 @@
|
||||||
"express": "^4.17.1",
|
"express": "^4.17.1",
|
||||||
"express-mongo-sanitize": "^2.0.0",
|
"express-mongo-sanitize": "^2.0.0",
|
||||||
"express-rate-limit": "^5.0.0",
|
"express-rate-limit": "^5.0.0",
|
||||||
|
"form-data": "^4.0.1",
|
||||||
|
"formdata-node": "^6.0.3",
|
||||||
"helmet": "^4.1.0",
|
"helmet": "^4.1.0",
|
||||||
"http-status": "^1.4.0",
|
"http-status": "^1.4.0",
|
||||||
|
"install": "^0.13.0",
|
||||||
"joi": "^17.3.0",
|
"joi": "^17.3.0",
|
||||||
"jsonwebtoken": "^8.5.1",
|
"jsonwebtoken": "^8.5.1",
|
||||||
|
"mariadb": "^3.4.0",
|
||||||
"moment": "^2.24.0",
|
"moment": "^2.24.0",
|
||||||
"mongoose": "^5.7.7",
|
"mongoose": "^8.7.1",
|
||||||
"morgan": "^1.9.1",
|
"morgan": "^1.9.1",
|
||||||
"mysql2": "^3.11.0",
|
"mysql2": "^3.11.0",
|
||||||
|
"node-fetch": "^3.3.2",
|
||||||
"nodemailer": "^6.3.1",
|
"nodemailer": "^6.3.1",
|
||||||
|
"npm": "^11.0.0",
|
||||||
"passport": "^0.4.0",
|
"passport": "^0.4.0",
|
||||||
"passport-jwt": "^4.0.0",
|
"passport-jwt": "^4.0.0",
|
||||||
"pm2": "^5.1.0",
|
"pm2": "^5.1.0",
|
||||||
|
@ -85,7 +92,6 @@
|
||||||
"eslint-plugin-prettier": "^3.1.1",
|
"eslint-plugin-prettier": "^3.1.1",
|
||||||
"eslint-plugin-security": "^1.4.0",
|
"eslint-plugin-security": "^1.4.0",
|
||||||
"faker": "^5.1.0",
|
"faker": "^5.1.0",
|
||||||
"husky": "7.0.4",
|
|
||||||
"jest": "^26.0.1",
|
"jest": "^26.0.1",
|
||||||
"lint-staged": "^11.0.0",
|
"lint-staged": "^11.0.0",
|
||||||
"node-mocks-http": "^1.8.0",
|
"node-mocks-http": "^1.8.0",
|
||||||
|
|
|
@ -38,7 +38,7 @@ module.exports = {
|
||||||
mongoose: {
|
mongoose: {
|
||||||
url: envVars.MONGODB_URL + (envVars.NODE_ENV === 'test' ? '-test' : ''),
|
url: envVars.MONGODB_URL + (envVars.NODE_ENV === 'test' ? '-test' : ''),
|
||||||
options: {
|
options: {
|
||||||
useCreateIndex: true,
|
// useCreateIndex: true,
|
||||||
useNewUrlParser: true,
|
useNewUrlParser: true,
|
||||||
useUnifiedTopology: true,
|
useUnifiedTopology: true,
|
||||||
},
|
},
|
||||||
|
|
|
@ -0,0 +1,12 @@
|
||||||
|
const mongoose = require("mongoose");
|
||||||
|
|
||||||
|
const gameSchema = new mongoose.Schema({
|
||||||
|
gameName: { type: String, required: true },
|
||||||
|
childId: { type: String, required: true },
|
||||||
|
gameID: { type: String, required: true },
|
||||||
|
gameTime: { type: String, required: false },
|
||||||
|
gameStar: { type: Number },
|
||||||
|
screenshotUrl: { type: String },
|
||||||
|
}, { collection: "gameData" });
|
||||||
|
|
||||||
|
module.exports = mongoose.model("Game", gameSchema);
|
|
@ -0,0 +1,15 @@
|
||||||
|
const mongoose = require('mongoose');
|
||||||
|
|
||||||
|
// Define the GalleryImage schema
|
||||||
|
const galleryImageSchema = new mongoose.Schema({
|
||||||
|
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 },
|
||||||
|
message: { type: String, default: 'Image received' },
|
||||||
|
}, { timestamps: true });
|
||||||
|
|
||||||
|
// Check if the model already exists in mongoose.models
|
||||||
|
const GalleryImage = mongoose.models.GalleryImage || mongoose.model('GalleryImage', galleryImageSchema);
|
||||||
|
|
||||||
|
module.exports = GalleryImage;
|
|
@ -0,0 +1,10 @@
|
||||||
|
const mongoose = require("mongoose");
|
||||||
|
|
||||||
|
const galleryImageScema = new mongoose.Schema({
|
||||||
|
gameName: { type: String, required: true },
|
||||||
|
childId: { type: String, required: true },
|
||||||
|
gameID: { type: String, required: true },
|
||||||
|
screenshotUrl: { type: String },
|
||||||
|
});
|
||||||
|
|
||||||
|
module.exports = mongoose.model("GalleryImage", galleryImageScema);
|
|
@ -0,0 +1,21 @@
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
|
||||||
|
function base64ToImageFile(base64, fileName) {
|
||||||
|
const matches = base64.match(/^data:(.+);base64,(.+)$/);
|
||||||
|
if (!matches) {
|
||||||
|
throw new Error("Invalid Base64 string");
|
||||||
|
}
|
||||||
|
|
||||||
|
const mimeType = matches[1]; // e.g., image/png
|
||||||
|
const base64Data = matches[2]; // Actual base64 string
|
||||||
|
|
||||||
|
const buffer = Buffer.from(base64Data, 'base64');
|
||||||
|
const filePath = path.join(__dirname, fileName);
|
||||||
|
|
||||||
|
fs.writeFileSync(filePath, buffer);
|
||||||
|
|
||||||
|
return filePath;
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { base64ToImageFile };
|
|
@ -0,0 +1,103 @@
|
||||||
|
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 aiEvaluateImageToScore = async (req, res) => {
|
||||||
|
try {
|
||||||
|
// Destructure data from req.body
|
||||||
|
const { userId, gameName, gameID, gameTime, gameStar, screenShot } = req.body;
|
||||||
|
|
||||||
|
if (!screenShot) {
|
||||||
|
return res.status(400).json({ error: 'Screenshot is required' });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Decode the base64 image
|
||||||
|
const buffer = Buffer.from(screenShot, 'base64');
|
||||||
|
const fileName = `${Date.now()}-${gameID}.png`; // Unique filename
|
||||||
|
const bucketName = process.env.S3_BUCKET_NAME;
|
||||||
|
|
||||||
|
// Initialize S3
|
||||||
|
AWS.config.update({
|
||||||
|
region: 'ap-south-1',
|
||||||
|
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
|
||||||
|
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
|
||||||
|
});
|
||||||
|
const s3 = new AWS.S3();
|
||||||
|
|
||||||
|
// Upload the image to S3
|
||||||
|
const s3Params = {
|
||||||
|
Bucket: bucketName,
|
||||||
|
Key: `screenshots/${fileName}`,
|
||||||
|
Body: buffer,
|
||||||
|
ContentType: 'image/png',
|
||||||
|
ACL: 'public-read', // Make the file publicly accessible
|
||||||
|
};
|
||||||
|
|
||||||
|
const s3UploadResponse = await s3.upload(s3Params).promise();
|
||||||
|
const screenshotUrl = s3UploadResponse.Location;
|
||||||
|
|
||||||
|
// Prepare the OpenAI API request
|
||||||
|
const openAiPayload = {
|
||||||
|
model: 'gpt-4o-mini',
|
||||||
|
messages: [
|
||||||
|
{
|
||||||
|
role: 'user',
|
||||||
|
content: [
|
||||||
|
{
|
||||||
|
type: 'text',
|
||||||
|
text: 'The coloring was done by a 5-year-old kid. Give a score between 1 to 10 in JSON format.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'image_url',
|
||||||
|
image_url: {
|
||||||
|
url: screenshotUrl,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
max_tokens: 300,
|
||||||
|
};
|
||||||
|
|
||||||
|
// Call the OpenAI API
|
||||||
|
const openAiResponse = await axios.post(
|
||||||
|
'https://api.openai.com/v1/chat/completions',
|
||||||
|
openAiPayload,
|
||||||
|
{
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
Authorization: `Bearer ${process.env.OPENAI_API_KEY}`,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
// Extract the score from OpenAI's response
|
||||||
|
const scoreResponse = openAiResponse.data.choices[0].message.content;
|
||||||
|
const parsedScore = JSON.parse(scoreResponse);
|
||||||
|
|
||||||
|
// Save to MongoDB
|
||||||
|
const gameData = new Game({
|
||||||
|
gameName,
|
||||||
|
userId,
|
||||||
|
gameID,
|
||||||
|
gameTime,
|
||||||
|
score: parsedScore.score || 'N/A', // Adjust key to match OpenAI response
|
||||||
|
gameStar,
|
||||||
|
screenshotUrl,
|
||||||
|
});
|
||||||
|
|
||||||
|
await gameData.save();
|
||||||
|
|
||||||
|
// Respond with the saved data
|
||||||
|
return res.status(201).json({
|
||||||
|
message: 'Game data saved successfully',
|
||||||
|
data: gameData,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error:', error.message);
|
||||||
|
return res.status(500).json({ error: 'Something went wrong' });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports = aiEvaluateImageToScore;
|
|
@ -0,0 +1,94 @@
|
||||||
|
const AWS = require('aws-sdk');
|
||||||
|
const axios = require('axios');
|
||||||
|
const mongoose = require('mongoose');
|
||||||
|
const FormData = require('form-data');
|
||||||
|
const Game = require('../../models/gameModel');
|
||||||
|
const aiEvaluateImageToStar = async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { childId, gameName, gameID, gameTime, gameStar, screenShot } = req.body;
|
||||||
|
if (!screenShot) {
|
||||||
|
return res.status(400).json({ error: 'Screenshot is required' });
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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: [
|
||||||
|
{
|
||||||
|
role: 'user',
|
||||||
|
content: [
|
||||||
|
{
|
||||||
|
type: 'text',
|
||||||
|
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,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
max_tokens: 300,
|
||||||
|
};
|
||||||
|
|
||||||
|
const openAiResponse = await axios.post(
|
||||||
|
'https://api.openai.com/v1/chat/completions',
|
||||||
|
openAiPayload,
|
||||||
|
{
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
Authorization: `Bearer ${process.env.OPENAI_API_KEY}`,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
|
||||||
|
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,
|
||||||
|
childId,
|
||||||
|
gameID,
|
||||||
|
gameTime,
|
||||||
|
gameStar: parsedScore.score || 'N/A',
|
||||||
|
screenshotUrl,
|
||||||
|
});
|
||||||
|
|
||||||
|
await gameData.save();
|
||||||
|
|
||||||
|
return res.status(200).json({
|
||||||
|
message: 'Game data saved successfully',
|
||||||
|
data: gameData,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error:', error.message);
|
||||||
|
return res.status(500).json({ error: error.message || 'Something went wrong' });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports = aiEvaluateImageToStar;
|
|
@ -0,0 +1,35 @@
|
||||||
|
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 payload = {
|
||||||
|
"model": "gpt-3.5-turbo-16k",
|
||||||
|
"messages": [{ "role": "user",
|
||||||
|
"content": JSON.stringify(req.body.grades) + " - first dataset(grades) " + JSON.stringify(req.body.suggested) + " - second dataset(suggested actions) " + req.body.instruction }]
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const apiResponse = await fetch(url, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'Authorization': `Bearer ${api_key}`,
|
||||||
|
// 'Authorization': api_key,
|
||||||
|
},
|
||||||
|
body: JSON.stringify(payload)
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!apiResponse.ok) {
|
||||||
|
return res.status(apiResponse.status).send({ error: 'API response was not ok'+res });
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = await apiResponse.json();
|
||||||
|
|
||||||
|
res.send(data);
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching data:', error);
|
||||||
|
res.status(500).send({ error: 'Something went wrong with the fetch operation' });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = aiFeedbackOnReport;
|
|
@ -0,0 +1,34 @@
|
||||||
|
const aiFeedbackOnReport = async (req, res) => {
|
||||||
|
// const fetch = require('node-fetch');
|
||||||
|
const url = process.env.AI_API_ENDOINT;
|
||||||
|
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 }]
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const apiResponse = await fetch(url, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'Authorization': `Bearer ${api_key}`,
|
||||||
|
// 'Authorization': api_key,
|
||||||
|
},
|
||||||
|
body: JSON.stringify(payload)
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!apiResponse.ok) {
|
||||||
|
return res.status(apiResponse.status).send({ error: 'API response was not ok'+res });
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = await apiResponse.json();
|
||||||
|
|
||||||
|
res.send(data);
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching data:', error);
|
||||||
|
res.status(500).send({ error: 'Something went wrong with the fetch operation' });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = aiFeedbackOnReport;
|
|
@ -0,0 +1,97 @@
|
||||||
|
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); // 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 = 600) {
|
||||||
|
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,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const data = await response.json();
|
||||||
|
return data;
|
||||||
|
// return data.choices[0].message.content;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
try {
|
||||||
|
const { prompt, sessionId, model = "gpt-4o-mini", max_tokens = 600 } = req.body;
|
||||||
|
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: 'You are a helpful assistant.' },
|
||||||
|
// { role: 'user', content: prompt },
|
||||||
|
{ 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 });
|
||||||
|
if (!conversation) {
|
||||||
|
return res.status(400).json({
|
||||||
|
success: false,
|
||||||
|
error: 'Invalid session ID.',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
conversation.conversationHistory.push({ role: 'user', content: prompt });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Call OpenAI API with the conversation history
|
||||||
|
const aiResponse = await fetchOpenAICompletion(prompt, conversation.conversationHistory, model, max_tokens);
|
||||||
|
|
||||||
|
// Add the AI's response to the conversation history
|
||||||
|
conversation.conversationHistory.push({ role: 'assistant', content: aiResponse });
|
||||||
|
|
||||||
|
// Update the conversation in MongoDB
|
||||||
|
await conversationsCollection.updateOne(
|
||||||
|
{ sessionId: conversation.sessionId },
|
||||||
|
{ $set: { conversationHistory: conversation.conversationHistory } }
|
||||||
|
);
|
||||||
|
|
||||||
|
// Send the AI's response and session ID back to the frontend
|
||||||
|
res.json({
|
||||||
|
success: true,
|
||||||
|
data: aiResponse,
|
||||||
|
sessionId: conversation.sessionId, // Return the session ID for subsequent queries
|
||||||
|
});
|
||||||
|
} 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;
|
|
@ -0,0 +1,123 @@
|
||||||
|
const aiFollowupQuestion = async (req, res) => {
|
||||||
|
// curl -X POST http://localhost:3000/your-endpoint-path \
|
||||||
|
// -H "Content-Type: application/json" \
|
||||||
|
// -d '{
|
||||||
|
// "prompt": "Why is the sky blue?",
|
||||||
|
// "sessionId": "",
|
||||||
|
// "model": "gpt-3.5-turbo-16k",
|
||||||
|
// "max_tokens": 200
|
||||||
|
// }'
|
||||||
|
|
||||||
|
// curl -X POST http://localhost:5174/api/aiFollowupQuestion \
|
||||||
|
// -H "Content-Type: application/json" \
|
||||||
|
// -d '{
|
||||||
|
// "prompt": "Why is the sky blue?",
|
||||||
|
// "sessionId": "",
|
||||||
|
// "model": "gpt-3.5-turbo-16k",
|
||||||
|
// "sessionId" : "8c641aca-582d-4ea7-8e56-4f94318efe74",
|
||||||
|
// "max_tokens": 200
|
||||||
|
// }'
|
||||||
|
|
||||||
|
// {
|
||||||
|
// "success": true,
|
||||||
|
// "data": "The sky looks blue because of how sunlight scatters in the air. Great question! Ask me more!",
|
||||||
|
// "total_tokens": 45,
|
||||||
|
// "sessionId": "2a3b3cc4-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
|
||||||
|
// }
|
||||||
|
|
||||||
|
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');
|
||||||
|
|
||||||
|
async function fetchOpenAICompletion(prompt, messages, model = 'gpt-3.5-turbo-16k', max_tokens = 200) {
|
||||||
|
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,
|
||||||
|
// 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const { prompt, sessionId, model = 'gpt-3.5-turbo-16k', max_tokens = 200 } = req.body;
|
||||||
|
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:
|
||||||
|
'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 },
|
||||||
|
],
|
||||||
|
};
|
||||||
|
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 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const aiResponse = await fetchOpenAICompletion(prompt, conversation.conversationHistory, model, max_tokens);
|
||||||
|
|
||||||
|
conversation.conversationHistory.push({ role: 'assistant', content: aiResponse.choices[0].message.content });
|
||||||
|
|
||||||
|
await conversationsCollection.updateOne(
|
||||||
|
{ sessionId: conversation.sessionId },
|
||||||
|
{ $set: { conversationHistory: conversation.conversationHistory } }
|
||||||
|
);
|
||||||
|
|
||||||
|
res.json({
|
||||||
|
success: true,
|
||||||
|
data: aiResponse.choices[0].message.content,
|
||||||
|
total_tokens: aiResponse.usage.total_tokens,
|
||||||
|
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;
|
|
@ -0,0 +1,116 @@
|
||||||
|
const aiMarkDrawing = async (req, res) => {
|
||||||
|
|
||||||
|
|
||||||
|
const express = require('express');
|
||||||
|
// const fetch = require('node-fetch'); // For making HTTP requests
|
||||||
|
const path = require('path');
|
||||||
|
const fs = require('fs');
|
||||||
|
|
||||||
|
// Create an Express app
|
||||||
|
const app = express();
|
||||||
|
const port = 3000;
|
||||||
|
|
||||||
|
// Middleware to handle JSON and URL-encoded form data
|
||||||
|
app.use(express.json());
|
||||||
|
app.use(express.urlencoded({ extended: true }));
|
||||||
|
|
||||||
|
// Replace with your OpenAI API key
|
||||||
|
const OPENAI_API_KEY = 'your-openai-api-key';
|
||||||
|
|
||||||
|
// Route to handle image upload and forward it to OpenAI API
|
||||||
|
app.post('/upload-image', async (req, res) => {
|
||||||
|
try {
|
||||||
|
// Check if the file is included in the request
|
||||||
|
if (!req.headers['content-type']?.includes('multipart/form-data')) {
|
||||||
|
return res.status(400).send({ message: 'No file uploaded' });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Extract the raw body data (binary) from the request
|
||||||
|
let imageBuffer = Buffer.alloc(0);
|
||||||
|
|
||||||
|
// Collect the image data from the stream (raw body)
|
||||||
|
req.on('data', chunk => {
|
||||||
|
imageBuffer = Buffer.concat([imageBuffer, chunk]);
|
||||||
|
});
|
||||||
|
|
||||||
|
req.on('end', async () => {
|
||||||
|
// Forward the image to OpenAI's API for scoring
|
||||||
|
const score = await sendImageToOpenAI(imageBuffer);
|
||||||
|
|
||||||
|
// Respond with the score
|
||||||
|
res.json({ score: score });
|
||||||
|
});
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error processing the image:', error);
|
||||||
|
res.status(500).send({ message: 'Internal Server Error' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Function to send image to OpenAI API and get the response
|
||||||
|
async function sendImageToOpenAI(imageBuffer) {
|
||||||
|
try {
|
||||||
|
// Convert binary image data to base64 format
|
||||||
|
const imageBase64 = imageBuffer.toString('base64');
|
||||||
|
|
||||||
|
// Make a request to the OpenAI API using fetch
|
||||||
|
const response = await fetch('https://api.openai.com/v1/chat/completions', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Authorization': `Bearer ${OPENAI_API_KEY}`,
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
model: "gpt-4-vision", // Use the appropriate model
|
||||||
|
messages: [
|
||||||
|
{ role: "system", content: "You are a grading assistant for 2nd grade students." },
|
||||||
|
{ role: "user", content: "Evaluate this student's drawing or coloring." }
|
||||||
|
],
|
||||||
|
functions: {
|
||||||
|
function_call: {
|
||||||
|
name: "vision_function",
|
||||||
|
args: {
|
||||||
|
image: imageBase64 // Send the image in base64 format
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
});
|
||||||
|
|
||||||
|
// Parse the response
|
||||||
|
const data = await response.json();
|
||||||
|
|
||||||
|
// Extract the score or other relevant information from the response
|
||||||
|
const aiResponse = data.choices[0].message.content;
|
||||||
|
|
||||||
|
// You can parse this response and extract the score, for example:
|
||||||
|
const score = extractScoreFromResponse(aiResponse);
|
||||||
|
return score;
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error interacting with OpenAI API:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Example function to extract a score from OpenAI's response (you need to define this based on the actual response structure)
|
||||||
|
function extractScoreFromResponse(responseText) {
|
||||||
|
// You can use a regex or logic to extract the score from OpenAI's response
|
||||||
|
const scoreMatch = responseText.match(/score:\s*(\d+)/i);
|
||||||
|
if (scoreMatch) {
|
||||||
|
return parseInt(scoreMatch[1], 10);
|
||||||
|
} else {
|
||||||
|
// If no score is found, return a default value
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Start the server
|
||||||
|
app.listen(port, () => {
|
||||||
|
console.log(`Server running at http://localhost:${port}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = aiMarkDrawing;
|
|
@ -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;
|
|
@ -0,0 +1,91 @@
|
||||||
|
const axios = require('axios');
|
||||||
|
const AWS = require('aws-sdk');
|
||||||
|
const FormData = require('form-data');
|
||||||
|
|
||||||
|
const aiTextToSpeech = async (req, res) => {
|
||||||
|
// curl -X POST http://localhost:5174/api/aiTextToSpeech \
|
||||||
|
// -H "Content-Type: application/json" \
|
||||||
|
// -d '{
|
||||||
|
// "text": "Hello, this is a sample speech.",
|
||||||
|
// "voiceId": "Ava"
|
||||||
|
// }'
|
||||||
|
|
||||||
|
// {"message":"Speech generated and saved successfully","fileUrls":["https://polly-bs.s3.ap-south-1.amazonaws.com/file_MpNpWluxR7R70BA-dzju_U3C94bPmC-n-speech.mp3?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAQ35B6OYR6T5MGH7Q%2F20250814%2Fap-south-1%2Fs3%2Faws4_request&X-Amz-Date=20250814T163252Z&X-Amz-Expires=86400&X-Amz-Signature=12dd2feaf73564d6c843b0dc975fdedb35c430d316f4f09fcdf41e247d1ea63c&X-Amz-SignedHeaders=host","https://polly-bs.s3.ap-south-1.amazonaws.com/file_SXmwHWwlcSBlI9LNoZ1PcLEdMD7D1PWO-text.txt?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAQ35B6OYR6T5MGH7Q%2F20250814%2Fap-south-1%2Fs3%2Faws4_request&X-Amz-Date=20250814T163252Z&X-Amz-Expires=86400&X-Amz-Signature=d96eb4fe7cabfab93ce0ffe8fc74a8e722a2064d904652d47ad361f2f3667ec7&X-Amz-SignedHeaders=host"],"fileKeys":{"file1":"file_MpNpWluxR7R70BA-dzju_U3C94bPmC-n-speech.mp3","file2":"file_SXmwHWwlcSBlI9LNoZ1PcLEdMD7D1PWO-text.txt"}}
|
||||||
|
|
||||||
|
AWS.config.update({
|
||||||
|
region: 'ap-south-1',
|
||||||
|
accessKeyId: process.env.AWS_polly2_ACCESS_KEY_ID,
|
||||||
|
secretAccessKey: process.env.AWS_polly2_SECRET_ACCESS_KEY,
|
||||||
|
});
|
||||||
|
|
||||||
|
const polly = new AWS.Polly();
|
||||||
|
const voiceIdMap = {
|
||||||
|
Ava: 'Ivy',
|
||||||
|
Monstero: 'Justin',
|
||||||
|
Dax: 'Kevin',
|
||||||
|
Kai: 'Danielle',
|
||||||
|
Arlo: 'Ruth',
|
||||||
|
Yara: 'Salli',
|
||||||
|
};
|
||||||
|
|
||||||
|
const { text, voiceId: frontendVoiceId } = req.body;
|
||||||
|
|
||||||
|
if (!text || !frontendVoiceId) {
|
||||||
|
return res.status(400).json({ error: 'Text and voiceId are required' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const pollyVoiceId = voiceIdMap[frontendVoiceId];
|
||||||
|
if (!pollyVoiceId) {
|
||||||
|
return res.status(400).json({ error: 'Invalid voiceId provided' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const params = {
|
||||||
|
Text: text,
|
||||||
|
OutputFormat: 'mp3',
|
||||||
|
Engine: 'neural',
|
||||||
|
VoiceId: pollyVoiceId,
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
function generateTimestampWithRandomDigits() {
|
||||||
|
const now = new Date();
|
||||||
|
const formattedDate = now.toISOString().replace('T', '_').replace(/\..+/, '').replace(/:/g, '-');
|
||||||
|
const randomDigits = Math.floor(Math.random() * 10000)
|
||||||
|
.toString()
|
||||||
|
.padStart(4, '0');
|
||||||
|
return `${formattedDate}_${randomDigits}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const folder = generateTimestampWithRandomDigits();
|
||||||
|
const folderName = `audio_files/${folder}`;
|
||||||
|
|
||||||
|
const data = await polly.synthesizeSpeech(params).promise();
|
||||||
|
const audioBuffer = data.AudioStream;
|
||||||
|
|
||||||
|
const textBuffer = Buffer.from(text, 'utf-8');
|
||||||
|
|
||||||
|
const formData = new FormData();
|
||||||
|
formData.append('file1', audioBuffer, 'speech.mp3');
|
||||||
|
formData.append('file2', textBuffer, 'text.txt');
|
||||||
|
// formData.append('folder', folderName); // Send folder name
|
||||||
|
formData.append('bucket', 'polly-bs'); // Adjust bucket
|
||||||
|
|
||||||
|
const response = await axios.post('https://preschool-curriculum.in/api/one/v1/file/upload', formData, {
|
||||||
|
headers: {
|
||||||
|
// 'Authorization': `Bearer ${process.env.BEARER_TOKEN}`,
|
||||||
|
...formData.getHeaders(), // Ensure FormData headers are included
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
res.json({
|
||||||
|
message: 'Speech generated and saved successfully',
|
||||||
|
fileUrls: response.data.urls,
|
||||||
|
fileKeys: response.data.data,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error generating speech or uploading files:', error);
|
||||||
|
res.status(500).json({ error: 'Error generating speech or uploading files' });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports = aiTextToSpeech;
|
|
@ -0,0 +1,35 @@
|
||||||
|
const mysql = require("mysql2");
|
||||||
|
|
||||||
|
const generateQuestions = (req, res) => {
|
||||||
|
const connection = mysql.createConnection({
|
||||||
|
host: process.env.MARIA_HOST,
|
||||||
|
user: process.env.MARIA_USER,
|
||||||
|
password: process.env.MARIA_PASS,
|
||||||
|
database: process.env.MARIA_DBNM
|
||||||
|
});
|
||||||
|
|
||||||
|
connection.connect((err) => {
|
||||||
|
if (err) {
|
||||||
|
console.error('Error connecting to the database:', err);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
console.log('Connected to the MariaDB database.');
|
||||||
|
});
|
||||||
|
|
||||||
|
const { questions } = req.body;
|
||||||
|
res.send( questions );
|
||||||
|
questions.forEach(question => {
|
||||||
|
const { questionText, options, correctAnswer } = question;
|
||||||
|
const sql = 'INSERT INTO quiz_questions (questionText, option1, option2, option3, option4, correctAnswer) VALUES (?, ?, ?, ?, ?, ?)';
|
||||||
|
db.query(sql, [questionText, options[0], options[1], options[2], options[3], correctAnswer], (err, result) => {
|
||||||
|
if (err) {
|
||||||
|
console.error('Error inserting question:', err);
|
||||||
|
res.status(500).send('Error inserting question');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
res.status(200).send('Questions added successfully');
|
||||||
|
}
|
||||||
|
module.exports = generateQuestions;
|
|
@ -1,35 +1,48 @@
|
||||||
const mysql = require("mysql2");
|
var MongoClient = require('mongodb').MongoClient;
|
||||||
|
// const AWS = require('aws-sdk');
|
||||||
|
|
||||||
const generateQuestions = (req, res) => {
|
const saveGameScore = (req, res) => {
|
||||||
const connection = mysql.createConnection({
|
const url = process.env.MONGODB_URL;
|
||||||
host: process.env.MARIA_HOST,
|
const dbName = process.env.MONGO_DB_NAME;
|
||||||
user: process.env.MARIA_USER,
|
const client = new MongoClient(url, { useUnifiedTopology: true });
|
||||||
password: process.env.MARIA_PASS,
|
client.connect((err) => {
|
||||||
database: process.env.MARIA_DBNM
|
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('questions');
|
||||||
|
// const data = req.body;
|
||||||
|
const { question, option1, option2, option3, option4, correctAnswer, moduleId } = req.body;
|
||||||
|
const data = {
|
||||||
|
question: question,
|
||||||
|
option1: option1,
|
||||||
|
option2: option2,
|
||||||
|
option3: option3,
|
||||||
|
option4: option4,
|
||||||
|
correctAnswer: correctAnswer,
|
||||||
|
moduleId: moduleId
|
||||||
|
};
|
||||||
|
|
||||||
connection.connect((err) => {
|
collection.insertOne(data, (err, result) => {
|
||||||
if (err) {
|
|
||||||
console.error('Error connecting to the database:', err);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
console.log('Connected to the MariaDB database.');
|
|
||||||
});
|
|
||||||
|
|
||||||
const { questions } = req.body;
|
|
||||||
res.send( questions );
|
|
||||||
questions.forEach(question => {
|
|
||||||
const { questionText, options, correctAnswer } = question;
|
|
||||||
const sql = 'INSERT INTO quiz_questions (questionText, option1, option2, option3, option4, correctAnswer) VALUES (?, ?, ?, ?, ?, ?)';
|
|
||||||
db.query(sql, [questionText, options[0], options[1], options[2], options[3], correctAnswer], (err, result) => {
|
|
||||||
if (err) {
|
if (err) {
|
||||||
console.error('Error inserting question:', err);
|
console.error('Failed to insert document', err);
|
||||||
res.status(500).send('Error inserting question');
|
} else {
|
||||||
return;
|
// 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');
|
||||||
|
|
||||||
|
res.send(result.insertedId);
|
||||||
|
}
|
||||||
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
};
|
||||||
res.status(200).send('Questions added successfully');
|
|
||||||
}
|
module.exports = saveGameScore;
|
||||||
module.exports = generateQuestions;
|
|
|
@ -0,0 +1,36 @@
|
||||||
|
const GalleryImage = require('../../models/getGalleyImage');
|
||||||
|
|
||||||
|
const getGalleryImage = async (req, res) => {
|
||||||
|
try {
|
||||||
|
// Extract query parameters for filtering (if provided)
|
||||||
|
const { gameName, childId, gameID} = req.query;
|
||||||
|
|
||||||
|
// Build a filter object based on the query parameters
|
||||||
|
const filter = {};
|
||||||
|
|
||||||
|
if (gameName) {
|
||||||
|
filter.gameName = gameName;
|
||||||
|
}
|
||||||
|
|
||||||
|
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 childId gameID screenshotUrl'); // Select only these fields
|
||||||
|
|
||||||
|
if (!galleryImages.length) {
|
||||||
|
return res.status(404).json({ message: 'No images found' });
|
||||||
|
}
|
||||||
|
|
||||||
|
return res.status(200).json(galleryImages); // Return the filtered gallery images with selected fields
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching images:', error.message);
|
||||||
|
return res.status(500).json({ error: 'Something went wrong' });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports = getGalleryImage;
|
|
@ -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;
|
|
@ -1,32 +1,56 @@
|
||||||
const mysql = require("mysql2");
|
|
||||||
const getGameScore = (req, res) => {
|
const getGameScore = (req, res) => {
|
||||||
const pool = mysql.createPool({
|
const { MongoClient } = require('mongodb');
|
||||||
host: process.env.MARIA_HOST,
|
|
||||||
user: process.env.MARIA_USER,
|
|
||||||
password: process.env.MARIA_PASS,
|
|
||||||
database: 'beanstalk_game',
|
|
||||||
waitForConnections: true,
|
|
||||||
connectionLimit: 10,
|
|
||||||
queueLimit: 0
|
|
||||||
});
|
|
||||||
const promisePool = pool.promise();
|
|
||||||
const { userId, gameName, gameID } = req.body;
|
|
||||||
|
|
||||||
const query = 'SELECT score, gameTime FROM gameData WHERE userId = ? AND gameName = ? AND gameID = ?';
|
async function main() {
|
||||||
|
const url = process.env.MONGODB_URL;
|
||||||
|
const dbName = process.env.MONGO_DB_NAME;
|
||||||
|
const client = new MongoClient(url, { useNewUrlParser: true, useUnifiedTopology: true });
|
||||||
|
|
||||||
pool.query(query, [userId, gameName, gameID], (error, results) => {
|
try {
|
||||||
if (error) {
|
// Connect to the MongoDB client
|
||||||
return res.status(500).json({ message: 'Database query failed', error });
|
await client.connect();
|
||||||
}
|
|
||||||
|
|
||||||
if (results.length > 0) {
|
// Select the database and collection
|
||||||
const game = results[0];
|
const database = client.db(dbName); // Replace with your database name
|
||||||
res.json({ score: game.score, gameTime: game.gameTime });
|
const collection = database.collection('gameData'); // Replace with your collection name
|
||||||
} else {
|
|
||||||
res.status(404).json({ message: 'Game data not found' });
|
// Find a single document
|
||||||
}
|
// const user = await collection.findOne({ childId: 'dsfdfgffgfgeg' });
|
||||||
});
|
|
||||||
};
|
const { childId, gameName, gameID } = req.body;
|
||||||
|
const gameData = await collection.findOne(
|
||||||
module.exports = getGameScore;
|
{
|
||||||
|
childId: childId,
|
||||||
|
gameName: gameName,
|
||||||
|
gameID: gameID
|
||||||
|
},{
|
||||||
|
sort: {_id: -1}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
// console.log('gameData', gameData);
|
||||||
|
if (gameData) {
|
||||||
|
res.json({gameData});
|
||||||
|
} else {
|
||||||
|
res.status(404).json({ message: 'Game data not found' });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Output the result
|
||||||
|
// if (user) {
|
||||||
|
// console.log('User found:', user);
|
||||||
|
// } else {
|
||||||
|
// console.log('No user found with the username "john_doe"');
|
||||||
|
// }
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error connecting to MongoDB or performing query:', error);
|
||||||
|
} finally {
|
||||||
|
// Close the connection
|
||||||
|
await client.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
main().catch(console.error);
|
||||||
|
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports = getGameScore;
|
||||||
|
|
|
@ -0,0 +1,79 @@
|
||||||
|
const GalleryImage = require('../../models/imageGallery');
|
||||||
|
const axios = require('axios');
|
||||||
|
const FormData = require('form-data'); // Import form-data for Node.js
|
||||||
|
|
||||||
|
const saveGalleryImage = async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { childId, gameName, gameID, screenShot } = req.body;
|
||||||
|
|
||||||
|
// Validate base64 format
|
||||||
|
const isValidBase64 = validateBase64(screenShot);
|
||||||
|
if (!isValidBase64) {
|
||||||
|
return res.status(400).json({ error: 'Invalid base64 image data' });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Extract image details
|
||||||
|
const imageData = extractImageDataFromBase64(screenShot);
|
||||||
|
const contentType = imageData.contentType || 'image/jpeg'; // Default to JPEG
|
||||||
|
|
||||||
|
// Convert base64 to buffer
|
||||||
|
const buffer = Buffer.from(screenShot.replace(/^data:image\/(png|jpg|jpeg);base64,/, ''), 'base64');
|
||||||
|
|
||||||
|
// Create FormData
|
||||||
|
const formData = new FormData();
|
||||||
|
formData.append('file1', buffer, { filename: 'screenshot.jpg', contentType });
|
||||||
|
formData.append('folder', 'gameGallery');
|
||||||
|
formData.append('bucket', 'polly-bs');
|
||||||
|
|
||||||
|
// Upload image to external API using axios
|
||||||
|
const uploadResponse = await axios.post(
|
||||||
|
'https://preschool-curriculum.in/api/one/v1/file/upload',
|
||||||
|
formData,
|
||||||
|
{
|
||||||
|
headers: {
|
||||||
|
...formData.getHeaders(), // Add form-data headers like Content-Type boundary
|
||||||
|
// Add any necessary authentication headers if required
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
if (uploadResponse.status !== 200) {
|
||||||
|
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({
|
||||||
|
childId,
|
||||||
|
gameName,
|
||||||
|
gameID,
|
||||||
|
screenshotUrl,
|
||||||
|
message: 'Image received',
|
||||||
|
});
|
||||||
|
await galleryImageData.save();
|
||||||
|
|
||||||
|
return res.status(200).json(galleryImageData);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error:', error.message);
|
||||||
|
return res.status(500).json({ error: 'Something went wrong' });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Validate base64 image
|
||||||
|
function validateBase64(base64String) {
|
||||||
|
const regex = /^data:image\/(png|jpg|jpeg);base64,/;
|
||||||
|
return regex.test(base64String);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Extract image data (like content type) from base64 string
|
||||||
|
function extractImageDataFromBase64(base64String) {
|
||||||
|
const matches = base64String.match(/^data:image\/(png|jpg|jpeg);base64,/);
|
||||||
|
return {
|
||||||
|
contentType: matches ? `image/${matches[1]}` : 'image/jpeg',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = saveGalleryImage;
|
|
@ -1,68 +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, screenShot } = req.body;
|
|
||||||
const data = {
|
|
||||||
userId: userId,
|
|
||||||
gameName: gameName,
|
|
||||||
gameID: gameID,
|
|
||||||
gameTime: gameTime,
|
|
||||||
score: score
|
|
||||||
};
|
|
||||||
|
|
||||||
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;
|
|
||||||
|
|
|
@ -0,0 +1,70 @@
|
||||||
|
const AWS = require("aws-sdk");
|
||||||
|
const mongoose = require("mongoose");
|
||||||
|
const Game = require("../../models/gameModel");
|
||||||
|
|
||||||
|
const s3 = new AWS.S3({
|
||||||
|
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
|
||||||
|
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
|
||||||
|
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 { childId, gameName, gameID, gameTime, score, gameStar, screenShot } = req.body;
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (!gameName || !childId || !gameID) {
|
||||||
|
return res.status(400).json({ error: "Missing required fields" });
|
||||||
|
}
|
||||||
|
|
||||||
|
const newGame = new Game({
|
||||||
|
gameName,
|
||||||
|
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 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,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error:", error);
|
||||||
|
res.status(500).json({ error: "Internal Server Error" });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports = saveGameScore2;
|
|
@ -22,7 +22,20 @@ const saveQuizResponse = require("../api/saveQuizResponse");
|
||||||
const getGameScore = require("../api/getGameScore");
|
const getGameScore = require("../api/getGameScore");
|
||||||
const resultAfterQuizSubmit = require("../api/resultAfterQuizSubmit");
|
const resultAfterQuizSubmit = require("../api/resultAfterQuizSubmit");
|
||||||
const generateQuestions = require("../api/generateQuestions");
|
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");
|
||||||
|
const aiFollowupQuestion = require("../api/aiFollowupQuestion");
|
||||||
|
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();
|
const router = express.Router();
|
||||||
|
@ -138,10 +151,74 @@ router.get("/ping", (req, res) => {
|
||||||
});
|
});
|
||||||
|
|
||||||
// For Quiz Result After Submit Quiz
|
// For Quiz Result After Submit Quiz
|
||||||
router.post("/saveGameScore", (req, res) => {
|
// router.post("/saveGameScore", (req, res) => {
|
||||||
saveGameScore(req, res);
|
// saveGameScore(req, res);
|
||||||
|
// });
|
||||||
|
|
||||||
|
// For Quiz Result After Submit Quiz
|
||||||
|
router.post("/saveGameScore2", (req, res) => {
|
||||||
|
saveGameScore2(req, res);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
|
// AI feedback for teacher on children's report card
|
||||||
|
router.post("/aiFeedbackOnReport", (req, res) => {
|
||||||
|
aiFeedbackOnReport(req, res);
|
||||||
|
});
|
||||||
|
// AI feedback for teacher on children's report card
|
||||||
|
router.post("/aiFeedbackOnReportWithFollowup", (req, res) => {
|
||||||
|
aiFeedbackOnReportWithFollowup(req, res);
|
||||||
|
});
|
||||||
|
|
||||||
|
// AI top ten action items for a parent of this child.
|
||||||
|
router.post("/aiFeedbackActionParent", (req, res) => {
|
||||||
|
aiFeedbackActionParent(req, res);
|
||||||
|
});
|
||||||
|
|
||||||
|
// AI to respond on initial and followup questions.
|
||||||
|
router.post("/aiFollowupQuestion", (req, res) => {
|
||||||
|
aiFollowupQuestion(req, res);
|
||||||
|
});
|
||||||
|
|
||||||
|
// AI to provide star for drawing.
|
||||||
|
router.post("/aiMarkDrawing", (req, res) => {
|
||||||
|
aiMarkDrawing(req, res);
|
||||||
|
});
|
||||||
|
|
||||||
|
// AI to provide star for drawing.
|
||||||
|
router.post("/aiTextToSpeech", (req, res) => {
|
||||||
|
aiTextToSpeech(req, res);
|
||||||
|
});
|
||||||
|
|
||||||
|
// AI to provide star for drawing.
|
||||||
|
router.post("/aiEvaluateImageToStar", (req, res) => {
|
||||||
|
aiEvaluateImageToStar(req, res);
|
||||||
|
});
|
||||||
|
|
||||||
|
// getGameInfo.
|
||||||
|
router.get("/getGameInfo", (req, res) => {
|
||||||
|
getGameInfo(req, res);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Save Drawing Game Gallery Image
|
||||||
|
router.post("/saveGalleryImage", (req, res) => {
|
||||||
|
saveGalleryImage(req, res);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Get Drawing Game Gallery Image
|
||||||
|
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;
|
module.exports = router;
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue