Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Develop participation #154

Merged
merged 47 commits into from
Apr 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
47 commits
Select commit Hold shift + click to select a range
3c7e8bf
Merge pull request #86 from Arquisoft/Develop
UO287687 Mar 5, 2024
0b16720
Added user context
uo276976 Mar 7, 2024
cfb7f92
addGame in PostGame
uo276976 Mar 11, 2024
56d6ac5
Avanzado contexto de usuario
uo276976 Mar 21, 2024
efca73b
Merge branch 'Develop-Participation' of https://github.com/Arquisoft/…
uo276976 Mar 21, 2024
75ac798
Tras registro login
uo276976 Mar 27, 2024
2157b61
fallo
uo276976 Mar 27, 2024
815e83a
updated some userContext
uo276976 Apr 1, 2024
acd2c05
error in test
uo276976 Apr 3, 2024
67c85b1
format
uo276976 Apr 3, 2024
216ff90
format
uo276976 Apr 3, 2024
a19b5a2
Game.test
uo276976 Apr 3, 2024
181379f
export defaukt
uo276976 Apr 3, 2024
722b046
format
uo276976 Apr 3, 2024
e12e968
no results
uo276976 Apr 3, 2024
d987962
session Context test
uo276976 Apr 3, 2024
1583c2c
AddUser test
uo276976 Apr 3, 2024
b997078
mockGoTo
uo276976 Apr 3, 2024
8e30c84
Merge branch 'Develop-Participation' into Develop
uo276976 Apr 3, 2024
9b4a055
Revert "Merge branch 'Develop-Participation' into Develop"
UO287687 Apr 4, 2024
eba121c
Question generation service test updated
UO287687 Apr 4, 2024
dce825e
Game.test
uo276976 Apr 4, 2024
227f774
Game test
uo276976 Apr 4, 2024
060cf93
act
uo276976 Apr 4, 2024
c2adf03
delete act
uo276976 Apr 4, 2024
4a97b72
act
uo276976 Apr 4, 2024
5ae07b3
goTo mock
uo276976 Apr 4, 2024
aa5d3c6
mockSetGameFinished
uo276976 Apr 4, 2024
69ca36f
moment
uo276976 Apr 4, 2024
6d9d3c6
act
uo276976 Apr 4, 2024
f3060db
Game test
uo276976 Apr 4, 2024
cf31e48
question test
uo276976 Apr 4, 2024
2e77cb8
act
uo276976 Apr 4, 2024
57264a0
fixing test
uo276976 Apr 4, 2024
f0af59d
Merge pull request #144 from Arquisoft/Develop
UO287747 Apr 4, 2024
0b8e634
fixing test
uo276976 Apr 4, 2024
88db089
Merge branch 'Develop-Participation' into Develop-ArreglarTestWebbApp
uo276976 Apr 5, 2024
e08ea10
como en develop
uo276976 Apr 5, 2024
25c4d3f
fixing tests
uo276976 Apr 5, 2024
0bd329e
Fix test
UO287747 Apr 5, 2024
2754a1c
Fix conflictos
UO287747 Apr 5, 2024
11e69c5
Merge branch 'Develop-Participation' into Develop-ArreglarTestWebbApp
UO287747 Apr 5, 2024
df67db8
Merge pull request #153 from Arquisoft/Develop-ArreglarTestWebbApp
UO287747 Apr 5, 2024
476482d
Changes from user context
uo276976 Apr 5, 2024
5339e41
Changes from UserContext
uo276976 Apr 5, 2024
582a031
participation test
uo276976 Apr 5, 2024
66f24fe
sonar quality
uo276976 Apr 5, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 5 additions & 7 deletions gameservice/game-model.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,16 @@
const mongoose = require('mongoose');

//usuario, preguntas[], respuestas[<String, bool>], tiempo

const gameSchema = new mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
type: String,
ref: 'User',
required: true,
},
questions: {
type: [mongoose.Schema.Types.ObjectId],
questions: [{
type: String,
ref: 'Question',
required: true,
},
}],
answers: [
{
response: {
Expand All @@ -33,4 +31,4 @@ const gameSchema = new mongoose.Schema({

const Game = mongoose.model('Game', gameSchema);

module.exports = Game;
module.exports = Game;
21 changes: 16 additions & 5 deletions gameservice/game-service.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
const express = require('express');
const mongoose = require('mongoose');
const Game = require('./game-model'); // Importa el modelo de juegos
const Game = require('./game-model');

const app = express();
const port = 8005; // Puerto para el servicio de juegos
Expand Down Expand Up @@ -29,8 +29,8 @@ app.post('/addgame', async (req, res) => {

// Crea una nueva instancia del modelo de juegos
const newGame = new Game({
user,
questions,
user: user,
questions: questions,
answers,
totalTime,
});
Expand All @@ -48,14 +48,23 @@ app.post('/addgame', async (req, res) => {
app.get('/getParticipation/:userId', async (req, res) => {
try {
const userId = req.params.userId;
console.log('User ID:', userId);

if (!userId) {
// Si no se encuentra el usuario, responder con un error
console.log('User not found');
res.status(404).json({ error: 'User not found' });
return;
}

// Consulta para obtener los datos de participación del usuario
console.log('Querying participation data...');
const participationData = await Game.aggregate([
{ $match: { user: mongoose.Types.ObjectId(userId) } },
{ $match: { user: userId } },
{
$group: {
_id: null,
totalGames: { $sum: 1 }, //$sum -> Returns a sum of numerical values
totalGames: { $sum: 1 }, //$sum -> Retorna la suma de los valores numéricos
correctAnswers: { $sum: { $size: {
$filter: {
input: "$answers", as: "answer", cond: "$$answer.isCorrect" }
Expand All @@ -70,10 +79,12 @@ app.get('/getParticipation/:userId', async (req, res) => {

if (participationData.length === 0) {
// No se encontraron datos para el usuario
console.log('No participation data found for the user.');
res.status(404).json({ error: 'No participation data found for the user.' });
return;
}

console.log('Sending participation data:', participationData[0]);
res.status(200).json(participationData[0]);
} catch (error) {
console.error('Error al obtener datos de participación:', error);
Expand Down
31 changes: 24 additions & 7 deletions gatewayservice/gateway-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
const authResponse = await axios.post(authServiceUrl+'/login', req.body);
res.json(authResponse.data);
} catch (error) {
res.status(500).json({ error: "Service down" });
res.status(error.response.status).json({ error: error.response.data.error });
}
});

Expand All @@ -43,7 +43,7 @@
const userResponse = await axios.post(userServiceUrl+'/adduser', req.body);
res.json(userResponse.data);
} catch (error) {
res.status(500).json({ error: "Service down" });
res.status(error.response.status).json({ error: error.response.data.error });
}
});

Expand All @@ -61,7 +61,7 @@
});
res.json(userResponse.data);
} catch (error) {
res.status(500).json({ error: "Service down" });
res.status(error.response.status).json({ error: error.response.data.error });
}
});

Expand All @@ -74,7 +74,7 @@
const infoResponse = await axios.get(url);
res.json(infoResponse.data);
} catch (error) {
res.status(500).json({ error: "Service down" });
res.status(error.response.status).json({ error: error.response.data.error });
}
});

Expand All @@ -85,7 +85,7 @@
const questionResponse = await axios.post(questionServiceUrl + '/addquestion', req.body);
res.json(questionResponse.data);
} catch (error) {
res.status(500).json({ error: "Service down" });
res.status(error.response.status).json({ error: error.response.data.error });
}
});

Expand All @@ -96,7 +96,24 @@
const gameResponse = await axios.post(gameServiceUrl + '/addgame', req.body);
res.json(gameResponse.data);
} catch (error) {
res.status(500).json({ error: "Service down" });
res.status(error.response.status).json({ error: error.response.data.error });
}
});

/// Ruta para obtener la participación del usuario
app.get('/getParticipation/:userId', async (req, res) => {
try {
const userId = req.params.userId;
if (!userId) {
res.status(404).json({ error: 'User ID not provided' });
return;
}
const apiUrl = `${gameServiceUrl}/getParticipation/${userId}`;
const gameResponse = await axios.get(apiUrl);
Dismissed Show dismissed Hide dismissed

res.json(gameResponse.data);
} catch (error) {
res.status(error.response.status).json({ error: error.response.data.error });
}
});

Expand All @@ -114,4 +131,4 @@
console.log(`Gateway Service listening at http://localhost:${port}`);
});

module.exports = server
module.exports = server
108 changes: 63 additions & 45 deletions question_generator/art/music/musicQuestions.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,23 @@
require('console');
const queryExecutor=require("../../queryExecutor")
const queryExecutor = require("../../queryExecutor");
const QuestionsUtils = require("../../questions-utils");
class MusicQuestions{
#musicQuestions=null;
static getInstance(){

class MusicQuestions {
#musicQuestions = null;

static getInstance() {
if (!this.questions) {
this.questions = new MusicQuestions();
}
return this.questions;
}
return this.questions;
}
constructor(){
this.data={}

constructor() {
this.data = {};
}
async loadValues(){
let result={};
const queries=[

async loadValues() {
let result = {};
const queries = [
`
SELECT ?cancion ?cancionLabel ?performerLabel
WHERE {
Expand All @@ -26,87 +29,102 @@ class MusicQuestions{
LIMIT 200
`
];
for(let i = 0; i <queries.length; i++) {

for (let i = 0; i < queries.length; i++) {
let query = queries[i];
let songs = await queryExecutor.execute(query);
songs.forEach(song=>{

songs.forEach(song => {
const songId = song.cancion.value.match(/Q\d+/)[0];
const songName = song.cancionLabel.value;
const performer = song.performerLabel.value;

if (!result[songId]) {
result[songId] = {
songId: songId,
name: songName,
performers: [],
}
};
}

result[songId].performers.push(performer);
});
}

return result;

}

async loadData(){
async loadData() {
let newResults = await this.loadValues();
const propertiesToLoad=[
const propertiesToLoad = [
{
name:'year',
name: 'year',
id: 'P577'
},
},
{
name: 'album',
id: 'P361'
}
]
for(let i = 0; i <Object.keys(newResults).length; i++) {
];

for (let i = 0; i < Object.keys(newResults).length; i++) {
let id = Object.keys(newResults)[i];
let r= await queryExecutor.executeQueryForEntityAndProperty(id, propertiesToLoad);
if(r.length>0){
for(let j=0;j<propertiesToLoad.length;j++){
if(r[0][propertiesToLoad[j].name]!==undefined){
let r = await queryExecutor.executeQueryForEntityAndProperty(id, propertiesToLoad);

if (r.length > 0) {
for (let j = 0; j < propertiesToLoad.length; j++) {
if (r[0][propertiesToLoad[j].name] !== undefined) {
newResults[id][propertiesToLoad[j].name] = r[0][propertiesToLoad[j].name].value;
}
}
}
}
this.data=newResults;

this.data = newResults;
}
async doQuestion(property,nValues){
if(Object.keys(this.data).length==0){

async doQuestion(property, nValues) {
if (Object.keys(this.data).length == 0) {
await this.loadData();
}

return QuestionsUtils.getValuesFromDataAndProperty(this.data, property, nValues);
}
async getRandomSong(numberOfSongs){
if(Object.keys(this.data).length==0){

async getRandomSong(numberOfSongs) {
if (Object.keys(this.data).length == 0) {
await this.loadData();
}

const array = Object.values(this.data);
const randomResults = array.sort(() => Math.random() - 0.5).slice(0, numberOfSongs);
return randomResults

return randomResults;
}

async getSongByPerformers() {
let numberOfSongs=4;
let result =(await this.getRandomSong(1))[0];
let numberOfSongs = 4;
let result = (await this.getRandomSong(1))[0];
let performers = result.performers.join(', ');

let correct = result.name;
let incorrects = []
let i=1;
while(i<numberOfSongs){
let song=(await this.getRandomSong(1))[0];
if(song.performers.join(', ')!=performers){
let incorrects = [];
let i = 1;

while (i < numberOfSongs) {
let song = (await this.getRandomSong(1))[0];

if (song.performers.join(', ') != performers) {
incorrects.push(song.name);
i++;
}
}

return {
performers:performers,
correct:correct,
incorrects:incorrects
}
performers: performers,
correct: correct,
incorrects: incorrects
};
}

}

module.exports = MusicQuestions;
2 changes: 2 additions & 0 deletions question_generator/entertainment/movies/moviesTemplates.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
const moviesQuestions=require('./moviesQuestions');
const moment = require('moment');

const moviesQuery=moviesQuestions.getInstance();
function loadData(){
moviesQuery.loadData();
Expand Down
23 changes: 11 additions & 12 deletions question_generator/queryExecutor.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@ const axios = require('axios');
class QueryExecutor{
static async execute(query) {
try {
const wikidataEndpoint = 'https://query.wikidata.org/sparql';
const wikidataEndpoint = 'https://query.wikidata.org/sparql';

// Configuración de la solicitud HTTP
const config = {
headers: {
'User-Agent': 'QueryExecutor/1.0 ([email protected])',
'Accept': 'application/json',
},
};
// Configuración de la solicitud HTTP
const config = {
headers: {
'User-Agent': 'QueryExecutor/1.0 ([email protected])',
'Accept': 'application/json',
},
};

const response = await axios.get(wikidataEndpoint, {
params: {
Expand All @@ -25,12 +25,11 @@ class QueryExecutor{
}
return response.data.results.bindings;



} catch (error) {
console.error('Error al realizar la consulta a Wikidata:', error.message, query);
console.error('Error al realizar la consulta a Wikidata:', error.message);
return []; // Return an empty array in case of error
}
}
}
static async executeQueryForEntityAndProperty(entity, properties){
if(!Array.isArray(properties) || properties.length==0){
return [];
Expand Down
Loading