Compare commits
69 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 5e741897c5 | |||
| 37316ff794 | |||
| f6835d9417 | |||
| 3cba906217 | |||
| 9f3f904a3a | |||
| 0038ee1b25 | |||
| b9d2e682c5 | |||
| ec27c1b366 | |||
| d3212fadbc | |||
| 9b9f841b12 | |||
|
|
e12308e8bb | ||
|
|
cdee582951 | ||
|
|
dc6194f7e7 | ||
|
|
6d380c6cbb | ||
|
|
8e0cce2465 | ||
|
|
0735a91450 | ||
|
|
1576fa92c1 | ||
|
|
319bc33d4a | ||
|
|
b7da294a17 | ||
|
|
0d4323df9e | ||
|
|
5da7710af1 | ||
| 76e503c4a9 | |||
|
|
59bcdcc3e8 | ||
| 91b73215be | |||
| 40eda82022 | |||
| 2150d52b9d | |||
| fb21f179e6 | |||
| 5777ee5131 | |||
| f96a50b7f4 | |||
| 3f944eb49e | |||
| ab74529965 | |||
| 73b3d67508 | |||
| 1706a910fd | |||
| f922617e57 | |||
| b7bc87908e | |||
| 23e5b2e329 | |||
| 571a079622 | |||
| 2d71ff105d | |||
| 6b1cad684d | |||
| d2db8ead08 | |||
| 1cf66178ae | |||
| 34e71a7dcf | |||
| abcfc2dbca | |||
| b77e3692d2 | |||
| 7db4089223 | |||
| e589d66e36 | |||
| cfa16dbdc7 | |||
| fe72636dd7 | |||
| f5d6c3cedc | |||
| 136286599f | |||
| 40c650f7d4 | |||
| b44c72e690 | |||
| 4acaac5b84 | |||
|
|
8f2f36bce0 | ||
| 22c2affa00 | |||
|
|
d38702698a | ||
| 0296de1703 | |||
| 9384390811 | |||
| 92974caef1 | |||
| 956d0a72bd | |||
| c67378c3f4 | |||
| e34abbb017 | |||
| a4e9e9cfb3 | |||
| 4d9a785812 | |||
| f68b1e78e0 | |||
| 87afa13a42 | |||
|
|
4d251402af | ||
|
|
d96461aedb | ||
|
|
b7b168b2d0 |
@@ -1,4 +0,0 @@
|
|||||||
#!/bin/sh
|
|
||||||
. "$(dirname "$0")/_/husky.sh"
|
|
||||||
|
|
||||||
yarn install
|
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
#!/bin/sh
|
|
||||||
. "$(dirname "$0")/_/husky.sh"
|
|
||||||
|
|
||||||
git status
|
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
#!/bin/sh
|
|
||||||
. "$(dirname "$0")/_/husky.sh"
|
|
||||||
|
|
||||||
yarn lint-staged
|
|
||||||
33
Dockerfile
33
Dockerfile
@@ -1,21 +1,26 @@
|
|||||||
ARG NODE_VERSION=18
|
# Use an official Node.js runtime as a parent image
|
||||||
|
FROM node:20-alpine
|
||||||
|
|
||||||
FROM node:${NODE_VERSION}-alpine
|
# Set the working directory inside the container
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
ENV NODE_ENV production
|
# Copy package files and set ownership
|
||||||
|
COPY --chown=node:node package*.json ./
|
||||||
|
|
||||||
RUN mkdir -p /usr/src/iimtt_api && chown -R node:node /usr/src/iimtt_api
|
# Install dependencies
|
||||||
|
RUN npm install --omit=dev
|
||||||
WORKDIR /usr/src/iimtt_api
|
|
||||||
|
|
||||||
COPY package.json yarn.lock ./
|
|
||||||
|
|
||||||
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 . .
|
||||||
|
|
||||||
EXPOSE 5174
|
# Use a non-root user for better security
|
||||||
|
USER node
|
||||||
|
|
||||||
CMD yarn start
|
# Expose the application port
|
||||||
|
EXPOSE 3000
|
||||||
|
|
||||||
|
# Set environment variables (optional)
|
||||||
|
ENV NODE_ENV=production
|
||||||
|
|
||||||
|
# Start the application
|
||||||
|
CMD ["npm", "run", "start"]
|
||||||
|
|||||||
22
game_links.txt
Normal file
22
game_links.txt
Normal file
@@ -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=
|
||||||
672
package-lock.json
generated
672
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
14
package.json
14
package.json
@@ -22,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",
|
||||||
@@ -49,23 +48,25 @@
|
|||||||
],
|
],
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"aws-sdk": "^2.1669.0",
|
"aws-sdk": "^2.1669.0",
|
||||||
"axios": "^1.7.7",
|
"axios": "^1.8.2",
|
||||||
"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",
|
||||||
"cors": "^2.8.5",
|
"cors": "^2.8.5",
|
||||||
"cross-env": "^7.0.0",
|
"cross-env": "^7.0.0",
|
||||||
"dotenv": "^10.0.0",
|
"dotenv": "^10.0.0",
|
||||||
"express": "^4.17.1",
|
"express": "^4.21.2",
|
||||||
"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",
|
"form-data": "^4.0.2",
|
||||||
"formdata-node": "^6.0.3",
|
"formdata-node": "^6.0.3",
|
||||||
|
"fs": "^0.0.1-security",
|
||||||
"helmet": "^4.1.0",
|
"helmet": "^4.1.0",
|
||||||
"http-status": "^1.4.0",
|
"http-status": "^1.4.0",
|
||||||
"install": "^0.13.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": "^8.7.1",
|
"mongoose": "^8.7.1",
|
||||||
"morgan": "^1.9.1",
|
"morgan": "^1.9.1",
|
||||||
@@ -75,7 +76,9 @@
|
|||||||
"npm": "^11.0.0",
|
"npm": "^11.0.0",
|
||||||
"passport": "^0.4.0",
|
"passport": "^0.4.0",
|
||||||
"passport-jwt": "^4.0.0",
|
"passport-jwt": "^4.0.0",
|
||||||
|
"path": "^0.12.7",
|
||||||
"pm2": "^5.1.0",
|
"pm2": "^5.1.0",
|
||||||
|
"puppeteer": "^24.4.0",
|
||||||
"swagger-jsdoc": "^6.0.8",
|
"swagger-jsdoc": "^6.0.8",
|
||||||
"swagger-ui-express": "^4.1.6",
|
"swagger-ui-express": "^4.1.6",
|
||||||
"validator": "^13.0.0",
|
"validator": "^13.0.0",
|
||||||
@@ -92,7 +95,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",
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
const aiFeedbackOnReport = async (req, res) => {
|
const aiFeedbackOnReport = async (req, res) => {
|
||||||
const fetch = require('node-fetch');
|
// const fetch = require('node-fetch');
|
||||||
const url = process.env.AI_API_ENDOINT;
|
const url = process.env.AI_API_ENDOINT;
|
||||||
const api_key = process.env.AI_API_KEY;
|
const api_key = process.env.AI_API_KEY;
|
||||||
const payload = {
|
const payload = {
|
||||||
|
|||||||
@@ -1,11 +1,10 @@
|
|||||||
const aiFeedbackOnReport = async (req, res) => {
|
const aiFeedbackOnReport = async (req, res) => {
|
||||||
// const fetch = require('node-fetch');
|
// const fetch = require('node-fetch');
|
||||||
const url = process.env.AI_API_ENDOINT;
|
const url = process.env.AI_API_ENDOINT;
|
||||||
const api_key = process.env.AI_API_KEY;
|
const api_key = process.env.OPENAI_KEY;
|
||||||
const payload = {
|
const payload = {
|
||||||
"model": "gpt-4o-mini",
|
"model": "gpt-4o-mini",
|
||||||
"messages": [{ "role": "user",
|
"messages": [{ "role": "user", "content": JSON.stringify(req.body.score) + " - is the students report card. " + req.body.instruction }]
|
||||||
"content": JSON.stringify(req.body.score) + " - is the students report card. " + req.body.instruction }]
|
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
const apiResponse = await fetch(url, {
|
const apiResponse = await fetch(url, {
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
const aiFollowupQuestion = async (req, res) => {
|
const aiFollowupQuestion = async (req, res) => {
|
||||||
|
|
||||||
const { MongoClient } = require('mongodb');
|
const { MongoClient } = require('mongodb');
|
||||||
const fetch = require('node-fetch');
|
// const fetch = require('node-fetch');
|
||||||
const { v4: uuidv4 } = require('uuid');
|
const { v4: uuidv4 } = require('uuid');
|
||||||
const url = process.env.MONGODB_URL;
|
const url = process.env.MONGODB_URL;
|
||||||
const dbName = process.env.MONGO_DB_NAME;
|
const dbName = process.env.MONGO_DB_NAME;
|
||||||
@@ -11,7 +11,7 @@ const aiFollowupQuestion = async (req, res) => {
|
|||||||
const database = client.db(dbName); // Replace with your database name
|
const database = client.db(dbName); // Replace with your database name
|
||||||
const conversationsCollection = database.collection('conversations'); // Replace with your collection name
|
const conversationsCollection = database.collection('conversations'); // Replace with your collection name
|
||||||
|
|
||||||
async function fetchOpenAICompletion(prompt, messages, model = "gpt-3.5-turbo-16k", max_tokens = 200) {
|
async function fetchOpenAICompletion(prompt, messages, model = "gpt-3.5-turbo-16k", max_tokens = 600) {
|
||||||
const response = await fetch('https://api.openai.com/v1/chat/completions', {
|
const response = await fetch('https://api.openai.com/v1/chat/completions', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
headers: {
|
||||||
@@ -26,12 +26,13 @@ const aiFollowupQuestion = async (req, res) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
return data.choices[0].message.content;
|
return data;
|
||||||
|
// return data.choices[0].message.content;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const { prompt, sessionId, model = "gpt-4o-mini", max_tokens = 200 } = req.body;
|
const { prompt, sessionId, model = "gpt-4o-mini", max_tokens = 600 } = req.body;
|
||||||
if (!conversationsCollection) {
|
if (!conversationsCollection) {
|
||||||
return res.status(500).json({
|
return res.status(500).json({
|
||||||
success: false,
|
success: false,
|
||||||
@@ -48,9 +49,10 @@ const aiFollowupQuestion = async (req, res) => {
|
|||||||
conversationHistory: [
|
conversationHistory: [
|
||||||
{ role: 'system', content: 'You are a helpful assistant.' },
|
{ role: 'system', content: 'You are a helpful assistant.' },
|
||||||
// { role: 'user', content: prompt },
|
// { role: 'user', content: prompt },
|
||||||
{ role: 'user', content: req.body.score + " - is the students report card. " + req.body.instruction },
|
{ role: 'user', content: JSON.stringify(req.body.score) + " - is the students report card. " + req.body.instruction },
|
||||||
],
|
],
|
||||||
};
|
};
|
||||||
|
// console.log(req.body.score[0])
|
||||||
await conversationsCollection.insertOne(conversation);
|
await conversationsCollection.insertOne(conversation);
|
||||||
} else {
|
} else {
|
||||||
conversation = await conversationsCollection.findOne({ sessionId: sessionId });
|
conversation = await conversationsCollection.findOne({ sessionId: sessionId });
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
const aiFollowupQuestion = async (req, res) => {
|
const aiFollowupQuestion = async (req, res) => {
|
||||||
|
|
||||||
const { MongoClient } = require('mongodb');
|
const { MongoClient } = require('mongodb');
|
||||||
const fetch = require('node-fetch');
|
// const fetch = require('node-fetch');
|
||||||
const { v4: uuidv4 } = require('uuid');
|
const { v4: uuidv4 } = require('uuid');
|
||||||
const url = process.env.MONGODB_URL;
|
const url = process.env.MONGODB_URL;
|
||||||
const dbName = process.env.MONGO_DB_NAME;
|
const dbName = process.env.MONGO_DB_NAME;
|
||||||
@@ -21,11 +21,17 @@ const aiFollowupQuestion = async (req, res) => {
|
|||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
model: model,
|
model: model,
|
||||||
messages: messages,
|
messages: messages,
|
||||||
|
// messages: [
|
||||||
|
// { role: "system", content: "reply must not exceed 20 words" },
|
||||||
|
// { role: "user", content: messages }
|
||||||
|
// ],
|
||||||
max_tokens: max_tokens,
|
max_tokens: max_tokens,
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
|
// console.log(process.env.OPENAI_KEY)
|
||||||
|
// console.log(data)
|
||||||
return data;
|
return data;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -46,7 +52,7 @@ const aiFollowupQuestion = async (req, res) => {
|
|||||||
conversation = {
|
conversation = {
|
||||||
sessionId: newSessionId,
|
sessionId: newSessionId,
|
||||||
conversationHistory: [
|
conversationHistory: [
|
||||||
{ role: 'system', content: 'answer within 50 words' },
|
{ role: 'system', content: 'answer within 10 words' },
|
||||||
{ role: 'user', content: prompt },
|
{ role: 'user', content: prompt },
|
||||||
],
|
],
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ const aiMarkDrawing = async (req, res) => {
|
|||||||
|
|
||||||
|
|
||||||
const express = require('express');
|
const express = require('express');
|
||||||
const fetch = require('node-fetch'); // For making HTTP requests
|
// const fetch = require('node-fetch'); // For making HTTP requests
|
||||||
const path = require('path');
|
const path = require('path');
|
||||||
const fs = require('fs');
|
const fs = require('fs');
|
||||||
|
|
||||||
|
|||||||
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, 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;
|
||||||
147
src/routes/api/getGameData.js
Normal file
147
src/routes/api/getGameData.js
Normal file
@@ -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;
|
||||||
136
src/routes/api/getGameInfo.js
Normal file
136
src/routes/api/getGameInfo.js
Normal file
@@ -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,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;
|
|
||||||
|
|
||||||
99
src/routes/api/takeSnap.js
Normal file
99
src/routes/api/takeSnap.js
Normal file
@@ -0,0 +1,99 @@
|
|||||||
|
const { execSync } = require("child_process");
|
||||||
|
const fs = require("fs");
|
||||||
|
const path = require("path");
|
||||||
|
const axios = require("axios");
|
||||||
|
|
||||||
|
const gameIds = [
|
||||||
|
'1', '2', '3', '4', '5', '6', '7', '8', '9', '10',
|
||||||
|
'11', '12', '13', '14', '15', '16', '17', '18', '19', '20',
|
||||||
|
'21', '22', '23', '24', '25', '26', '27', '28', '29', '30',
|
||||||
|
'31', '32', '33', '34', '35', '36', '37', '38', '39', '40',
|
||||||
|
'41', '42', '43', '44', '45', '46', '47', '48', '49', '50',
|
||||||
|
'51', '52', '53', '54', '55', '56', '57', '58', '59', '60',
|
||||||
|
'61', '62', '63', '64', '65', '66', '67', '68', '69', '70',
|
||||||
|
'71', '72', '73', '74', '75', '76', '77', '78', '79', '80',
|
||||||
|
'81', '82', '83', '84', '85', '86', '87', '88', '89', '90',
|
||||||
|
'91', '92', '93', '94', '95', '96', '97', '98', '99', '100',
|
||||||
|
'101', '102', '103', '104', '105', '114'
|
||||||
|
];
|
||||||
|
|
||||||
|
const SCREENSHOT_FOLDER = path.join(__dirname, "game-screen/drawing");
|
||||||
|
if (!fs.existsSync(SCREENSHOT_FOLDER)) {
|
||||||
|
fs.mkdirSync(SCREENSHOT_FOLDER, { recursive: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
const DIRECTUS_API_URL = "https://game-du.teachertrainingkolkata.in/files";
|
||||||
|
|
||||||
|
async function takeSnap(req, res) {
|
||||||
|
for (const id of gameIds) {
|
||||||
|
try {
|
||||||
|
const url = `https://interaktogames.beanstalkedu.com/tick/v1?id=${id}`;
|
||||||
|
console.log(`📸 Taking screenshot for Game ID: ${id}`);
|
||||||
|
const command = `url2jpg ${url}`;
|
||||||
|
execSync(command, { stdio: "inherit", shell: true });
|
||||||
|
const files = fs.readdirSync(process.cwd()).filter(f => f.endsWith(".jpg"));
|
||||||
|
if (files.length === 0) throw new Error("No screenshot found!");
|
||||||
|
|
||||||
|
const latestFile = files.reduce((a, b) =>
|
||||||
|
fs.statSync(b).mtimeMs > fs.statSync(a).mtimeMs ? b : a
|
||||||
|
);
|
||||||
|
const newPath = path.join(SCREENSHOT_FOLDER, `${id}.jpg`);
|
||||||
|
fs.renameSync(latestFile, newPath);
|
||||||
|
console.log(`✅ Screenshot saved: ${newPath}`);
|
||||||
|
const fileId = await uploadToDirectus(newPath);
|
||||||
|
if (fileId) {
|
||||||
|
console.log(`📤 Uploaded to Directus. File ID: ${fileId}`);
|
||||||
|
await updateThumbnail(id, fileId);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error(`❌ Error processing Game ID ${id}:`, error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
res.json({ message: "All screenshots processed successfully!" });
|
||||||
|
}
|
||||||
|
|
||||||
|
async function uploadToDirectus(filePath) {
|
||||||
|
try {
|
||||||
|
const fileData = fs.createReadStream(filePath);
|
||||||
|
|
||||||
|
const response = await axios.post(
|
||||||
|
DIRECTUS_API_URL,
|
||||||
|
{ file: fileData },
|
||||||
|
{
|
||||||
|
headers: { "Content-Type": "multipart/form-data" },
|
||||||
|
}
|
||||||
|
);
|
||||||
|
return response.data.data.id;
|
||||||
|
} catch (error) {
|
||||||
|
console.error("❌ Failed to upload screenshot to Directus:", error.message);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
async function updateThumbnail(gameId, fileId) {
|
||||||
|
const UPDATE_THUMBNAIL_URL = "https://game-du.teachertrainingkolkata.in/items/game_tick_variant1/";
|
||||||
|
try {
|
||||||
|
const response = await axios.patch(
|
||||||
|
`${UPDATE_THUMBNAIL_URL}${gameId}`,
|
||||||
|
{ thumbnail: fileId }, // ✅ No need for "data" wrapper in REST API
|
||||||
|
{ headers: { "Content-Type": "application/json" } }
|
||||||
|
);
|
||||||
|
console.log(`✅ Thumbnail updated for Game ID ${gameId}:`, response.data);
|
||||||
|
} catch (error) {
|
||||||
|
console.error(`❌ Failed to update thumbnail for Game ID ${gameId}`);
|
||||||
|
if (error.response) {
|
||||||
|
console.error("Response Data:", error.response.data);
|
||||||
|
console.error("Status Code:", error.response.status);
|
||||||
|
} else {
|
||||||
|
console.error("Error Message:", error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
module.exports = takeSnap;
|
||||||
@@ -22,7 +22,7 @@ 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 saveGameScore2 = require("../api/saveGameScore2");
|
||||||
const aiFeedbackOnReport = require("../api/aiFeedbackOnReport");
|
const aiFeedbackOnReport = require("../api/aiFeedbackOnReport");
|
||||||
const aiFeedbackActionParent = require("../api/aiFeedbackActionParent");
|
const aiFeedbackActionParent = require("../api/aiFeedbackActionParent");
|
||||||
@@ -31,9 +31,11 @@ const aiMarkDrawing = require("../api/aiMarkDrawing");
|
|||||||
const aiFeedbackOnReportWithFollowup = require("../api/aiFeedbackOnReportWithFollowup");
|
const aiFeedbackOnReportWithFollowup = require("../api/aiFeedbackOnReportWithFollowup");
|
||||||
const aiTextToSpeech = require("../api/aiTextToSpeech");
|
const aiTextToSpeech = require("../api/aiTextToSpeech");
|
||||||
const aiEvaluateImageToStar = require("../api/aiEvaluateImageToStar");
|
const aiEvaluateImageToStar = require("../api/aiEvaluateImageToStar");
|
||||||
// const getGameInfo = require("../api/getGameInfo");
|
const getGameInfo = require("../api/getGameInfo");
|
||||||
const saveGalleryImage = require("../api/saveGalleryImage");
|
const saveGalleryImage = require("../api/saveGalleryImage");
|
||||||
const getGalleryImage = require("../api/getGalleryImage");
|
const getGalleryImage = require("../api/getGalleryImage");
|
||||||
|
const getGameData = require("../api/getGameData");
|
||||||
|
const takeSnap = require("../api/takeSnap");
|
||||||
// const aiTest = require("../api/aiTest");
|
// const aiTest = require("../api/aiTest");
|
||||||
|
|
||||||
|
|
||||||
@@ -150,9 +152,9 @@ 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
|
// For Quiz Result After Submit Quiz
|
||||||
router.post("/saveGameScore2", (req, res) => {
|
router.post("/saveGameScore2", (req, res) => {
|
||||||
@@ -195,9 +197,9 @@ router.get("/ping", (req, res) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// getGameInfo.
|
// getGameInfo.
|
||||||
// router.get("/getGameInfo", (req, res) => {
|
router.get("/getGameInfo", (req, res) => {
|
||||||
// getGameInfo(req, res);
|
getGameInfo(req, res);
|
||||||
// });
|
});
|
||||||
|
|
||||||
// Save Drawing Game Gallery Image
|
// Save Drawing Game Gallery Image
|
||||||
router.post("/saveGalleryImage", (req, res) => {
|
router.post("/saveGalleryImage", (req, res) => {
|
||||||
@@ -209,6 +211,14 @@ router.get("/ping", (req, res) => {
|
|||||||
getGalleryImage(req, res);
|
getGalleryImage(req, res);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
router.get("/getGameData", (req, res) => {
|
||||||
|
getGameData(req, res);
|
||||||
|
});
|
||||||
|
|
||||||
|
router.get("/takeSnap", (req, res) => {
|
||||||
|
takeSnap(req, res);
|
||||||
|
});
|
||||||
|
|
||||||
// Get Drawing Game Gallery Image
|
// Get Drawing Game Gallery Image
|
||||||
// router.post("/aiTest", (req, res) => {
|
// router.post("/aiTest", (req, res) => {
|
||||||
// aiTest(req, res);
|
// aiTest(req, res);
|
||||||
|
|||||||
Reference in New Issue
Block a user