Skip to content

Commit

Permalink
Merge pull request #336 from EthicApp-Development/issue-291-rebase
Browse files Browse the repository at this point in the history
[ethicapp-v2-ca] Implementación de interacciones entre backend de EthicApp y servicio de análisis de contenido #290, #291
  • Loading branch information
claudio-alvarez committed Jun 14, 2024
2 parents 198d54c + 3ab4478 commit f6055bb
Show file tree
Hide file tree
Showing 10 changed files with 143 additions and 13 deletions.
3 changes: 3 additions & 0 deletions .env
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,6 @@ ETHICAPP_ENV=development

# Origin for CORS
ALLOWED_ORIGINS=http://localhost:3000

#API validation key
API_VALIDATION_KEY=DevelopmentApiKey
4 changes: 3 additions & 1 deletion content-analysis/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
migrate = Migrate(app, db, compare_type=True)
#from models import Comments, Process, Topics

validation_api_key = os.environ.get("API_VALIDATION_KEY")
redis_host_name = os.environ.get("REDIS_HOST_NAME")
if not redis_host_name:
redis_host_name = 'localhost'
Expand Down Expand Up @@ -130,7 +131,8 @@ def filter_comments(comments_list):
@celery.task(name= 'client_callback', max_retry=10, default_retry_delay=3*60)
def client_callback(result):
url = result['context']['callback_url']
response = requests.post(url,json=result)
headers = {'x-api-key': validation_api_key}
response = requests.post(url, json=result, headers=headers)
return {'result': result}

def extract_text_from_pdf_url(pdf_url):
Expand Down
7 changes: 5 additions & 2 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ services:
CONTENT_ANALYSIS_HOST_NAME: ${CONTENT_ANALYSIS_HOST_NAME}
CONTENT_ANALYSIS_PORT: ${CONTENT_ANALYSIS_PORT}
NODE_HOST_NAME: ${NODE_HOST_NAME}
API_VALIDATION_KEY: ${API_VALIDATION_KEY}
restart: "no"
networks:
default:
Expand Down Expand Up @@ -125,7 +126,8 @@ services:
volumes:
- .:/app
environment:
- REDIS_HOST_NAME=${REDIS_HOST_NAME}
REDIS_HOST_NAME: ${REDIS_HOST_NAME}
API_VALIDATION_KEY: ${API_VALIDATION_KEY}
depends_on:
- RedisContainer

Expand All @@ -138,7 +140,8 @@ services:
- .:/app
command: ['celery', '-A', 'content-analysis.app.celery', 'worker', '-P', 'solo', '-l', 'info', '-Q', 'celery', '-n', '"celery"']
environment:
- REDIS_HOST_NAME=${REDIS_HOST_NAME}
REDIS_HOST_NAME: ${REDIS_HOST_NAME}
API_VALIDATION_KEY: ${API_VALIDATION_KEY}
depends_on:
- content-analysis
- RedisContainer
3 changes: 3 additions & 0 deletions ethicapp/backend/config/socket.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,7 @@ module.exports.configSocket = function(io){
module.exports.chatMsgStage = function(stageid, tmid){
io.of("/").emit("chatMsgStage", {stageid: stageid, tmid: tmid});
};
module.exports.contentUpdate = function(sesid, data){
io.of("/").emit("contentUpdate", {ses: sesid, data: data});
};
};
61 changes: 53 additions & 8 deletions ethicapp/backend/controllers/visor.js
Original file line number Diff line number Diff line change
Expand Up @@ -409,15 +409,15 @@ async function buildContentAnalysisUnit(req, res) {
return acc;
}, {});

const nodeHostName = process.env.NODE_HOST_NAME

const sessionURL = `http://${nodeHostName}:${process.env.NODE_PORT}/${result[0].case_url}`;
const nodeHostName = process.env.NODE_HOST_NAME;
const nodePort = process.env.NODE_PORT;
const sessionURL = `http://${nodeHostName}:${nodePort}/${result[0].case_url}`;

const workUnitJson = {
context: {
session_id: result[0].session_id,
phase_id: result[0].phase_id,
callback_url: "http://host.docker.internal:3000/test",
callback_url: `http://${nodeHostName}:${nodePort}/content-analysis-callback`,
timestamp: Date.now(),
},
content: {
Expand All @@ -432,7 +432,6 @@ async function buildContentAnalysisUnit(req, res) {
}))
}
};
console.log(workUnitJson);
resolve(workUnitJson);
}
})(req,res);
Expand All @@ -441,8 +440,8 @@ async function buildContentAnalysisUnit(req, res) {

async function sendContentAnalysisWorkunit(workunit){
try {
const contentAnalysisHostName = process.env.CONTENT_ANALYSIS_HOST_NAME
const contentAnalysisPort = process.env.CONTENT_ANALYSIS_PORT
const contentAnalysisHostName = process.env.CONTENT_ANALYSIS_HOST_NAME;
const contentAnalysisPort = process.env.CONTENT_ANALYSIS_PORT;
const response = await fetch(`http://${contentAnalysisHostName}:${contentAnalysisPort}/top-worst`, {
method: 'POST',
headers: {
Expand All @@ -459,6 +458,53 @@ async function sendContentAnalysisWorkunit(workunit){
}
}

router.post('/content-analysis-callback', async (req, res) => {
try {

const data = req.body;

const stageNumber = data.context.phase_id;
req.body.stage_number = stageNumber;
req.body.sesid = data.context.session_id;

rpg.execSQL({
dbcon: pass.dbcon,
sql: `
WITH ROWS AS (
UPDATE content_analysis
SET response_selections = $1,
context = $2
WHERE sesid = $3
AND stage_number = $4
RETURNING 1
)
INSERT INTO content_analysis(response_selections, context, sesid, stage_number)
SELECT $5,
$6,
$7,
$8
WHERE 1 NOT IN (
SELECT *
FROM ROWS
)
`,
preventResEnd: true,
sesReqData: ["ses"],
postReqData: ["response_selections", "context", "stage_number"],
sqlParams: [
rpg.param("post", "response_selections"), rpg.param("post", "context"), rpg.param("post", "sesid"),
rpg.param("post", "stage_number"), rpg.param("post", "response_selections"), rpg.param("post", "context"),
rpg.param("post", "sesid"), rpg.param("post", "stage_number")
]
})(req,res);

socket.contentUpdate(req.session.ses, data);

} catch (error) {
console.error('Error al procesar el callback:', error);
}
});

router.post("/send-diff-selection", (req, res, next) => {

rpg.singleSQL({
Expand All @@ -480,7 +526,6 @@ router.post("/send-diff-selection", (req, res, next) => {
handleQuestionCounter(redisKey).then(isCounterTenOrMore => {
if (true) { // MODIFICAR A "isCounterTenOrMore" PARA SU FUNCIONAMIENTO
buildContentAnalysisUnit(req, res).then(workUnitJson => {
console.log(workUnitJson);
sendContentAnalysisWorkunit(workUnitJson);
})
.catch(error => {
Expand Down
4 changes: 4 additions & 0 deletions ethicapp/backend/middleware/validate-session.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@ module.exports.verifySession = (req, res, next) => {
if (req.isAuthenticated()) {
return next();
}
const apiKey = req.headers['x-api-key'];
if (apiKey && apiKey === `${process.env.API_VALIDATION_KEY}`) {
return next();
}
res.redirect("/login");
};

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*eslint func-style: ["error", "expression"]*/
export let DashboardController = ($scope, ActivityStateService,
export let DashboardController = ($scope, $socket,ActivityStateService,
$http, $timeout, $uibModal, Notification) => {

var self = $scope;
Expand All @@ -10,6 +10,53 @@ export let DashboardController = ($scope, ActivityStateService,
self.dataChatCount = {};
self.activityState = ActivityStateService;

self.init = self.init = function () {
console.log("iteracion:", self.iterationIndicator);
console.log("session id:", self.selectedSes.id)
$socket.on("contentUpdate", (data) => {
if(data.data.sesid === self.selectedSes.id){
console.log("Datos coinciden con la sesión actual:", data);
self.contentAnalysis = data;
const questionId = data.data.response_selections[0].question_id;

if (!self.contentAnalysis[self.selectedSes.id]) {
self.contentAnalysis[self.selectedSes.id] = {};
}

if (!self.contentAnalysis[self.selectedSes.id][questionId]) {
self.contentAnalysis[self.selectedSes.id][questionId] = {
top: [],
worst: []
};
}
/*
if (!self.contentAnalysis[self.selectedSes.id]) {
self.contentAnalysis[self.selectedSes.id] = {
top: [],
worst: []
};
}
*/
angular.forEach(data.data.response_selections, function(selection) {
angular.forEach(selection.responses, function(response) {
if (response.ranking_type === 'top') {
self.contentAnalysis[self.selectedSes.id][questionId].top[response.ranking - 1] = response.response_text;
} else if (response.ranking_type === 'worst') {
self.contentAnalysis[self.selectedSes.id][questionId].worst[response.ranking - 1] = response.response_text;
}
});
});

console.log(self.contentAnalysis)

} else {
console.log("Datos no coinciden con la sesión actual:");
}
});

console.log("DashboardController inicializado.");
};

self.shared.resetGraphs = function () { //THIS HAS TO BE CALLED ON ADMIN
if (
(self.selectedSes.type == "R") ||
Expand Down Expand Up @@ -1030,4 +1077,5 @@ export let DashboardController = ($scope, ActivityStateService,
return self.shared.groupByUid[a].index - self.shared.groupByUid[b].index;
};

self.init();
};
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ adpp.controller("SesEditorController",
adpp.controller("NewUsersController",
["$scope", "$http", "Notification", IncomingUsersController]);
adpp.controller("DashboardController",
["$scope", "ActivityStateService", "$http", "$timeout", "$uibModal", "Notification", DashboardController]);
["$scope", "$socket","ActivityStateService", "$http", "$timeout", "$uibModal", "Notification", DashboardController]);
adpp.controller("MapSelectionModalController",
["$scope", "$uibModalInstance", MapSelectionModalController]);
adpp.controller("ConfirmModalController",
Expand Down
15 changes: 15 additions & 0 deletions ethicapp/frontend/views/partials/teacher/activity.html
Original file line number Diff line number Diff line change
Expand Up @@ -369,6 +369,21 @@ <h4>{{'details' | translate}} {{'report' | translate}}:</h4>
</div>

<div ng-show="design.type == 'semantic_differential'" class="margin-top-8">
<h2>Rubrica</h2>
<table class="table table-bordered">
<thead>
<tr>
<th>Top</th>
<th>Worst</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="index in [].constructor(contentAnalysis['1']['1'].top.length) track by $index">
<td>{{ contentAnalysis['1']['1'].top[$index] }}</td>
<td>{{ contentAnalysis['1']['1'].worst[$index] }}</td>
</tr>
</tbody>
</table>
<strong>{{ 'indAggAns' | translate }}</strong>
<span class="pull-right mt-1medio margin-right-8"><span style="color: red;">*</span> {{
'commentReq' | translate }}</span>
Expand Down
7 changes: 7 additions & 0 deletions postgres-db/schema/create_39.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
CREATE TABLE content_analysis (
id SERIAL PRIMARY KEY,
response_selections text,
context text,
sesid integer REFERENCES sessions(id),
stage_number integer
);

0 comments on commit f6055bb

Please sign in to comment.