Commit a327feb7 authored by Anastasios Kalogeropoulos's avatar Anastasios Kalogeropoulos
Browse files

Merge branch 'bug/multiple-connections'

parents 3371f95a b4c5f8bb
PORT=the-port-of-the-server
SLACK_APP_PORT=the-port-of-the-server
FACILITATOR_STATUS_HANDLER_PORT=port-of-the-facilitator-status-handler-server
BOT_OATH_TOKEN=your-bot-use-oauth-access-token
OATH_TOKEN=your-oath-access-token
CHANNEL=the-channel-id, e.g. C012AB3CD for a general channel
\ No newline at end of file
CHANNEL=the-channel-id, e.g. C012AB3CD for a general channel
UHH_IDEA_DB_URL=url-of-the-experiment-ideadb
FACILITATOR_STATUS_URL=url-of-the-facilitor-handler-server
\ No newline at end of file
const axios = require('axios');
const {uhhIdeaDB, facilitatorStatusUrl} = require('./config');
class APIService {
constructor() {
this.uhhIdeaDB = 'https://civitasdigitalis.fortiss.org/experiment-uhh/ideadb/idea/';
}
getIdeaById(id) {
return axios.get(this.uhhIdeaDB + `byId?id=${id}`)
return axios.get(uhhIdeaDB + `byId?id=${id}`)
.then(response => {
let received_idea = response.data;
console.log(received_idea);
......@@ -17,6 +17,19 @@ class APIService {
});
}
changeFacilitatorState(status) {
const params = { 'status': status.toString() };
return axios.post(facilitatorStatusUrl + 'facilitator/newStatus', params, {responseType: 'text'});
}
getFacilitatorStatus() {
return axios.get(facilitatorStatusUrl + 'facilitator/status').then(status => {
return status;
}).catch(error => {
console.log('Error getting facilitator\'s status', error);
});
}
updateIdeaById(idea, history) {
idea["theInterface"] = idea.theInterface.name;
let keywords = [];
......@@ -27,7 +40,7 @@ class APIService {
idea["keywords"] = keywords;
idea["conversation_history"] = history;
axios.put(`${this.uhhIdeaDB}update`, idea).then(function (response) {
axios.put(`${uhhIdeaDB}update`, idea).then(function (response) {
console.log("Idea updated successfully");
})
.catch(function (error) {
......
module.exports = {
port: process.env.PORT,
port: process.env.SLACK_APP_PORT,
facilitatorStatusHandlerPort: process.env.FACILITATOR_STATUS_HANDLER_PORT,
botOathToken: process.env.BOT_OATH_TOKEN,
oathToken: process.env.OATH_TOKEN,
channel: process.env.CHANNEL
channel: process.env.CHANNEL,
uhhIdeaDB: process.env.UHH_IDEA_DB_URL,
facilitatorStatusUrl: process.env.FACILITATOR_STATUS_URL
};
\ No newline at end of file
const {facilitatorStatusHandlerPort} = require('./config');
const express = require('express')
const cors = require('cors')
const bodyParser = require('body-parser');
const app = express()
const port = 2999
app.use(bodyParser.json());
app.use(cors())
......@@ -16,7 +15,7 @@ let facilitatorState = true;
* false: facilitator cannot handle conversation
*/
app.get('/facilitator/status', cors(), (req, res) => {
console.log('Status change request');
console.log('GET facilitator status request');
let response = {"available": facilitatorState};
res.send(response)
})
......@@ -28,10 +27,10 @@ app.post('/facilitator/newStatus', cors(), (req, res) => {
let status = req.body['status'];
if(status === "true" || status === "false") {
facilitatorState = JSON.parse(status);
res.send("Status changed successfully to: " + facilitatorState.toString());
res.send("POST facilitator status " + facilitatorState.toString());
} else {
res.send("Cannot process request");
}
})
app.listen(port, () => console.log(`Facilitator status handler listening on port ${port}!`))
\ No newline at end of file
app.listen(facilitatorStatusHandlerPort, () => console.log(`Facilitator status handler listening on port ${facilitatorStatusHandlerPort}!`))
\ No newline at end of file
......@@ -4,7 +4,7 @@
"description": "",
"main": "slack-server.js",
"scripts": {
"start": "concurrently \"node -r dotenv/config slack-server.js\" \"node facilitator-status-handler.js\" ",
"start": "concurrently \"node -r dotenv/config slack-server.js\" \"node -r dotenv/config facilitator-status-handler.js\" ",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
......
......@@ -12,8 +12,6 @@ const Helper = require('./helper');
//initialize a simple http server
const server = http.createServer(app);
const wss = new WebSocket.Server({ server, path: '/webplugin' }); // Accept only connections matching this path
const apiService = new APIService();
const END_OF_CONVERSATION_TEXT = "END_OF_CONVERSATION"
......@@ -28,66 +26,81 @@ rtm.start();
let currentClient = "";
wss.on('connection', (ws) => {
let uuid = uuidv4();
connectedClients.push(new Client(ws, uuid))
console.log("Connection established")
rtm.sendMessage("New user connected! ", channel)
.then((res) => {
// `res` contains information about the posted message
console.log('Message sent: ', res.ts);
})
.catch(console.error);
ws.on('message', (wsMessage) => {
let incomingMessage = JSON.parse(wsMessage);
console.log('-------------------');
console.log(incomingMessage);
console.log('-------------------');
const ws = new WebSocket.Server({ server, path: '/webplugin' }); // Accept only connections matching this path
ws.on('connection', (connection_ws) => {
apiService.getFacilitatorStatus().then(status => {
// refuse empty messages
if (typeof incomingMessage !== 'object') {
ws.send("404");
return;
}
// refuse bad requests
if (!incomingMessage['recipient'] || !incomingMessage['recipient']['id']) {
ws.send("400");
return;
}
currentClient = connectedClients.find(obj => {
return obj.uuid === incomingMessage['sender']['id'];
});
//Receive message from Web plugin --> send it to slack
if (incomingMessage['message']) {
let incomingText = incomingMessage['message']['text'];
console.log("Incoming message: ", incomingText);
currentClient.saveMessageInHistory(incomingText, "INCOMING");
rtm.sendMessage(incomingText, channel)
.then((res) => {
// `res` contains information about the posted message
console.log('Message sent: ', res.ts);
})
.catch(console.error);
let availability = status['data']['available'];
console.log(availability);
if(availability) {
apiService.changeFacilitatorState(false).then(resp => {
console.log(resp);
});
let uuid = uuidv4();
connectedClients.push(new Client(connection_ws, uuid))
console.log("Connection established")
rtm.sendMessage("New user connected! ", channel)
.then((res) => {
// `res` contains information about the posted message
console.log('Message sent: ', res.ts);
})
.catch(console.error);
connection_ws.on('message', (wsMessage) => {
let incomingMessage = JSON.parse(wsMessage);
console.log('-------------------');
console.log(incomingMessage);
console.log('-------------------');
// refuse empty messages
if (typeof incomingMessage !== 'object') {
connection_ws.send("404");
return;
}
// refuse bad requests
if (!incomingMessage['recipient'] || !incomingMessage['recipient']['id']) {
connection_ws.send("400");
return;
}
currentClient = connectedClients.find(obj => {
return obj.uuid === incomingMessage['sender']['id'];
});
//Receive message from Web plugin --> send it to slack
if (incomingMessage['message']) {
let incomingText = incomingMessage['message']['text'];
console.log("Incoming message: ", incomingText);
currentClient.saveMessageInHistory(incomingText, "INCOMING");
rtm.sendMessage(incomingText, channel)
.then((res) => {
// `res` contains information about the posted message
console.log('Message sent: ', res.ts);
})
.catch(console.error);
}
});
let conversationStatus = getConversationStatus(connection_ws, uuid);
connection_ws.send(JSON.stringify(conversationStatus));
} else {
console.log("Cannot accept new connection");
}
});
let conversationStatus = getConversationStatus(ws, uuid);
ws.send(JSON.stringify(conversationStatus));
});
wss.on('close', (ws) => {
ws.on('close', (ws) => {
console.log("Connection Closed")
});
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment