Compare commits
38 Commits
8f2f36bce0
...
suvo-patch
| Author | SHA1 | Date | |
|---|---|---|---|
| 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 | |||
| 22c2affa00 | |||
|
|
7dda27e86e | ||
|
|
5152ca2e23 |
BIN
output.png
Normal file
BIN
output.png
Normal file
Binary file not shown.
2553
package-lock.json
generated
2553
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -60,8 +60,10 @@
|
||||
"express-mongo-sanitize": "^2.0.0",
|
||||
"express-rate-limit": "^5.0.0",
|
||||
"form-data": "^4.0.1",
|
||||
"formdata-node": "^6.0.3",
|
||||
"helmet": "^4.1.0",
|
||||
"http-status": "^1.4.0",
|
||||
"install": "^0.13.0",
|
||||
"joi": "^17.3.0",
|
||||
"jsonwebtoken": "^8.5.1",
|
||||
"mariadb": "^3.4.0",
|
||||
@@ -69,7 +71,9 @@
|
||||
"mongoose": "^8.7.1",
|
||||
"morgan": "^1.9.1",
|
||||
"mysql2": "^3.11.0",
|
||||
"node-fetch": "^3.3.2",
|
||||
"nodemailer": "^6.3.1",
|
||||
"npm": "^11.0.0",
|
||||
"passport": "^0.4.0",
|
||||
"passport-jwt": "^4.0.0",
|
||||
"pm2": "^5.1.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 },
|
||||
});
|
||||
|
||||
21
src/module/base64ToImageFile.js
Normal file
21
src/module/base64ToImageFile.js
Normal file
@@ -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 };
|
||||
@@ -1,30 +1,27 @@
|
||||
const AWS = require('aws-sdk');
|
||||
const axios = require('axios');
|
||||
const FormData = require('form-data');
|
||||
const mongoose = require('mongoose');
|
||||
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: [
|
||||
@@ -33,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 3 to 5 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,
|
||||
},
|
||||
},
|
||||
],
|
||||
@@ -47,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 +54,29 @@ const aiEvaluateImageToStar = async (req, res) => {
|
||||
},
|
||||
}
|
||||
);
|
||||
const rResp=openAiResponse.data.choices[0].message;
|
||||
const cleanContent = rResp.content.replace(/```json|```/g, '').trim();
|
||||
const parsedScore = JSON.parse(cleanContent);
|
||||
// console.log(parsedScore); // { score: 8 }
|
||||
|
||||
|
||||
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',
|
||||
gameStar,
|
||||
screenshotUrl:screenshotUrl.data.filePath,
|
||||
gameStar: parsedScore.score || 'N/A',
|
||||
screenshotUrl,
|
||||
});
|
||||
|
||||
await gameData.save();
|
||||
@@ -80,7 +87,7 @@ const parsedScore = JSON.parse(cleanContent);
|
||||
});
|
||||
} 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' });
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -30,8 +30,8 @@ const aiFollowupQuestion = async (req, res) => {
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
console.log(process.env.OPENAI_KEY)
|
||||
console.log(data)
|
||||
// console.log(process.env.OPENAI_KEY)
|
||||
// console.log(data)
|
||||
return data;
|
||||
}
|
||||
|
||||
|
||||
166
src/routes/api/aiTest.js
Normal file
166
src/routes/api/aiTest.js
Normal file
@@ -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 } = 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: 'answer within 10 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 });
|
||||
}
|
||||
|
||||
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' });
|
||||
|
||||
@@ -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");
|
||||
@@ -34,6 +34,7 @@ const aiEvaluateImageToStar = require("../api/aiEvaluateImageToStar");
|
||||
const getGameInfo = require("../api/getGameInfo");
|
||||
const saveGalleryImage = require("../api/saveGalleryImage");
|
||||
const getGalleryImage = require("../api/getGalleryImage");
|
||||
// const aiTest = require("../api/aiTest");
|
||||
|
||||
|
||||
const router = express.Router();
|
||||
@@ -149,9 +150,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) => {
|
||||
@@ -207,6 +208,11 @@ router.get("/ping", (req, res) => {
|
||||
router.get("/getGalleryImage", (req, res) => {
|
||||
getGalleryImage(req, res);
|
||||
});
|
||||
|
||||
// Get Drawing Game Gallery Image
|
||||
// router.post("/aiTest", (req, res) => {
|
||||
// aiTest(req, res);
|
||||
// });
|
||||
|
||||
|
||||
module.exports = router;
|
||||
|
||||
Reference in New Issue
Block a user