-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
104 lines (89 loc) · 2.57 KB
/
server.js
File metadata and controls
104 lines (89 loc) · 2.57 KB
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
const express = require("express");
const http = require("http");
const socketIo = require("socket.io");
const math = require("mathjs");
const cors = require("cors");
const uuidv1 = require("uuid/v1");
const content = require("./content");
const API_PORT = 3001;
const MESSAGE_TIMEOUT = 1000;
const app = express();
app.use(cors({ origin: "http://localhost:3000" }));
const server = http.Server(app);
const io = socketIo(server);
// In-memory replacement for an actual db based session storage (like redis)
const sessionStorage = {};
/*
Generates a unique token to identify sessions
*/
app.get("/generate-token", (req, res) => {
const token = uuidv1();
sessionStorage[token] = {};
res.send({ token });
});
io.on("connection", socket => {
socket.on("HandshakeFromUser", data => {
if (!data.token) {
return error(`Missing token`);
}
// this can only happen if the session storage is lost due to a server restart
if (!sessionStorage[data.token]) {
sessionStorage[data.token] = {};
}
const session = sessionStorage[data.token];
if (session.userName) {
send(socket, [
content.repeat_greeting(session.userName),
content.list_math_expression
]);
} else {
send(socket, [content.introduction, content.name_prompt]);
}
});
socket.on("MessageFromUser", data => {
if (!data.token) {
return error(`Missing token`);
}
var session = sessionStorage[data.token];
if (!session) {
return error(`Session not found`);
}
if (session.userName) {
try {
const num = math.eval(data.content.toLowerCase());
send(socket, [num.toString(), content.success_response]);
} catch (e) {
send(socket, [content.failure_response]);
}
} else {
const firstName = data.content.split(" ")[0];
session.userName = firstName;
send(socket, [
content.first_greeting(firstName),
content.explanation_prompt,
content.list_math_expression
]);
}
});
});
/*
Sends a list of messages one by one, simulates typing
*/
function send(socket, messages) {
let i = 0;
const interval = setInterval(() => {
if (i < messages.length) {
socket.emit("MessageFromBot", { isTyping: true });
setTimeout(() => {
socket.emit("MessageFromBot", { text: messages[i] });
i++;
}, MESSAGE_TIMEOUT);
} else {
clearInterval(interval);
}
}, MESSAGE_TIMEOUT);
}
function error(message) {
socket.emit("Error", { message });
}
server.listen(API_PORT, () => console.log(`Listening on port ${API_PORT}`));