This repository was archived by the owner on Apr 16, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathws_server.js
355 lines (325 loc) · 13.1 KB
/
ws_server.js
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
/*
Authors:
Adam Stück, Bianca Kevy, Cecilie Hejlesen
Frederik Stær, Lasse Rasmussen and Tais Hors
Group: DAT2 - C1-14
Date: 27/05-2020
This file contains the Websocket server used for the interaction
between the public and the dispatcher side.
Here the server endpoints are created manually with a switch.
*/
const fs = require('fs');
const server = require('ws').Server;
const s = new server({ port: 3001 });
const Case = require("./databaseModels/caseModel").Case;
let dispatchers = [];
let cases = [];
let counter = 0;
let caseObj;
console.log("Listening on port 3001...");
// For connecting to the MongoDB server when archiving cases
const mongoose = require("mongoose");
const mongoDbUrl = 'mongodb+srv://dev:dev@clustercms-faqog.gcp.mongodb.net/cmsdb?retryWrites=true&w=majority';
/* Configure Mongoose to Connect to MongoDB */
mongoose.connect(mongoDbUrl, { useNewUrlParser: true, useUnifiedTopology: true })
.then(response => {
console.log("MongoDB Connected Successfully.");
}).catch(err => {
console.log("Database connection failed.");
});
loadCases();
// Server handling events
s.on('connection', function(client) {
// A client has sent a message to the server.
client.on('message', function(message) {
let data = JSON.parse(message);
// Handle the message depending on what type it has.
switch(data.type) {
case "dispatcherConnect":
// A dispatcher has connected to the server.
dispatchers.push(client);
cases.forEach(function(entry) {
client.send(JSON.stringify(simpleCase(entry)));
});
break;
case "case":
// New case submitted to the server.
// Give the case an ID and save the client that created for live chat, then send the case to all dispatchers.
data.id = ++counter;
data.citizen = client;
data.dispatcher = null;
data.timeDate = new Date().toLocaleDateString();
data.timeClock = getTimeClock();
data.chatLog = [];
data.notes = "";
console.log("Case created (id: %d)", data.id);
cases.push(data);
client.send(JSON.stringify({
type: "caseCreated",
id: data.id
}));
broadcastToDispatchers(simpleCase(data));
saveCases();
break;
case "requestOpenCase":
// A dispatcher wants to view a case. Allow if the case is available, reject if it is taken
caseObj = getCaseByID(data.id);
if (caseObj != null) {
if (caseObj.dispatcher == null) {
caseObj.dispatcher = client;
// Send the case details to the dispatcher.
client.send(JSON.stringify(fullCase(caseObj)));
// Notify citizen that a dispatcher is now viewing the case.
sendChatMessage(caseObj.citizen, "A dispatcher is now viewing your case...");
// Update the case list for all dispatchers so they can see the case is no longer available.
broadcastToDispatchers({
type: "caseOpened",
id: data.id
})
} else {
// The case is not available. Deny the dispatcher's request.
client.send(JSON.stringify({
type: "denyOpenCase"
}));
}
}
break;
case "closeCase":
// A dispatcher has closed a case. Make the case available to other dispatchers again.
caseObj = getCaseByID(data.id);
if (caseObj != null) {
caseObj.dispatcher = null;
// Notify the citizen that a dispatcher is no longer viewing their case.
sendChatMessage(caseObj.citizen, "A dispatcher has put your case on hold...");
broadcastToDispatchers({
type: "caseClosed",
id: data.id
});
}
break;
case "chatMessage":
// Send a chat message. If it is sent from a dispatcher, forward the message to citizen.
// If the message comes from citizen, forward it to the dispatcher.
caseObj = getCaseByID(data.id);
if (caseObj != null) {
if (data.dispatcher)
sendChatMessage(caseObj.citizen, data.message);
else
sendChatMessage(caseObj.dispatcher, data.message);
caseObj.chatLog.push(data.message);
saveCases();
}
break;
case "saveName":
// An dispatcher has edited the Name field in a patient journal
caseObj = getCaseByID(data.id);
if (caseObj != null) {
caseObj.name = data.value;
saveCases();
}
break;
case "savePhone":
// A dispatcher has edited the Phone field in a patient journal
caseObj = getCaseByID(data.id);
if (caseObj != null) {
caseObj.phone = data.value;
saveCases();
}
break;
case "saveCPR":
// A dispatcher has edited the CPR field in a patient journal
caseObj = getCaseByID(data.id);
if (caseObj != null) {
caseObj.cpr = data.value;
saveCases();
}
break;
case "saveNotes":
// A dispatcher has edited the Notes field in a patient journal
caseObj = getCaseByID(data.id);
if (caseObj != null) {
caseObj.notes = data.value;
saveCases();
}
break;
case "requestReopenCase":
// A citizen wants to open an already existing case
caseObj = getCaseByID(data.id);
if (caseObj != null) {
if(caseObj.citizen) {
// Reject because there is already a citizen viewing the case.
client.send(JSON.stringify({
type: "denyReopenCase",
reason: 1
}));
} else {
caseObj.citizen = client;
client.send(JSON.stringify({
type: "allowReopenCase",
id: data.id,
chatLog: caseObj.chatLog
}));
let msg = "The citizen has reconnected...";
sendChatMessage(caseObj.dispatcher, msg);
}
} else {
// Reject because the case has been archived.
client.send(JSON.stringify({
type: "denyReopenCase",
reason: 2
}));
}
break;
case "archiveCase":
// A dispatcher wants to archive a case
caseObj = getCaseByID(data.id);
if (caseObj != null) {
// Let all dispatcher know so it gets removed from their case list.
broadcastToDispatchers(data);
sendChatMessage(caseObj.citizen, "Your case has now been closed. Further communication is not possible.");
// Send the case to MongoDB.
const newCase = new Case({
id: caseObj.id,
name: caseObj.name,
phone: caseObj.phone,
cpr: caseObj.cpr,
pos: caseObj.pos,
desc: caseObj.desc,
notes: caseObj.notes,
chatLog: caseObj.chatLog,
timeClock: caseObj.timeClock,
timeDate: caseObj.timeDate
});
newCase.save().then(post => {
console.log("Case archived (id: %d)", caseObj.id);
});
// Remove the case from the cases.txt [] array
let i = cases.indexOf(caseObj);
cases.splice(i, 1);
saveCases();
}
break;
default:
// This should never happen
console.log("Received some weird data...");
break;
}
});
// A client has disconnected.
client.on('close', function() {
// Check if they are in the dispatcher array.
// If they are, remove them from the array.
let i = dispatchers.indexOf(client);
if (i !== -1) {
// If the dispatcher had a case open, make it available to other dispatchers.
cases.forEach(function(entry) {
if(entry.dispatcher == client) {
entry.dispatcher = null;
sendChatMessage(entry.citizen, "A dispatcher has put your case on hold...");
broadcastToDispatchers({
type: "caseClosed",
id: entry.id
});
}
});
dispatchers.splice(i, 1);
} else {
// Not a dispatcher, check if they created a case.
cases.forEach(function(entry) {
if(entry.citizen == client) {
entry.citizen = null;
let msg = "The citizen has disconnected...";
sendChatMessage(entry.dispatcher, msg);
}
});
}
});
});
// Sends a chat message to the client without logging it in a case.
// Useful for chat notifications.
function sendChatMessage(client, msg) {
if (client != null)
client.send(JSON.stringify({type: "chatMessage", message: msg}));
}
// Returns the case object with a specific id from the cases[] array.
function getCaseByID(id) {
for (let i = 0; i < cases.length; i++) {
if(cases[i].id == id)
return cases[i];
}
return null;
}
// Lite version of a case. This is all the data needed for adding it to the dispatcher's case list.
function simpleCase(data) {
return {
type: "case",
id: data.id,
pos: data.pos,
available: (data.dispatcher == null),
timeClock: data.timeClock
};
}
// Full version of a case. This is all the data needed for the chat and patient journal.
function fullCase(data) {
return {
type: "allowOpenCase",
id: data.id,
name: data.name,
phone: data.phone,
cpr: data.cpr,
desc: data.desc,
notes: data.notes,
chatLog: data.chatLog,
timeClock: data.timeClock,
timeDate: data.timeDate
};
}
// Sends data to all connected dispatchers
function broadcastToDispatchers(data) {
dispatchers.forEach(function(dispatcher) {
dispatcher.send(JSON.stringify(data));
});
}
// What time is it? This is the time created for cases
function getTimeClock() {
let time = new Date();
let hours = time.getHours();
let minutes = time.getMinutes();
let seconds = time.getSeconds();
if (hours < 10)
hours = `0${hours}`;
if (minutes < 10)
minutes = `0${minutes}`;
if (seconds < 10)
seconds = `0${seconds}`
return hours + ":" + minutes + ":" + seconds;
}
// Saves current cases to txt file, which can be loaded in the case of a server restart/crash.
function saveCases() {
// Delete any already existing data in save file
fs.truncate('cases.txt', 0, function(){});
// Write this simplified cases array to a file the server can read from next time it starts.
fs.writeFile('cases.txt', JSON.stringify(cases, ["type", "id", "name", "phone", "cpr", "desc", "notes", "chatLog", "timeClock", "timeDate", "pos", "lat", "lng"], 4), (err) => {
if (err) {
console.log("Failed to save cases. " + err);
}
});
}
// Load current cases from file
function loadCases() {
console.log("Loading active cases from previous session...");
fs.readFile('cases.txt', {encoding: 'utf-8'}, function(err, data){
if(err) {
console.log("Failed to read cases.txt. " + err);
} else {
try {
cases = JSON.parse(data);
console.log("Loaded " + cases.length + " cases.");
if(cases.length > 0)
counter = cases[cases.length-1].id;
} catch(jsonError) {
console.log("There were no cases to load or cases.txt is broken.");
}
}
});
}