forked from sfbrigade/bats-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwss.js
181 lines (171 loc) · 5.62 KB
/
wss.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
const querystring = require('querystring');
const { Op } = require('sequelize');
const url = require('url');
const WebSocket = require('ws');
const DeliveryStatus = require('./constants/deliveryStatus');
const models = require('./models');
const userServer = new WebSocket.Server({ noServer: true });
userServer.on('connection', async (ws, req) => {
// eslint-disable-next-line no-param-reassign
ws.info = { userId: req.user.id, organizationId: req.user.OrganizationId };
// eslint-disable-next-line no-use-before-define
const data = await getRingdownData(req.user.id);
ws.send(data);
});
const hospitalServer = new WebSocket.Server({ noServer: true });
hospitalServer.on('connection', async (ws, req) => {
// eslint-disable-next-line no-param-reassign
ws.info = { userId: req.user.id, hospitalId: req.hospital.id };
// eslint-disable-next-line no-use-before-define
const data = await getStatusUpdateData(req.hospital.id);
ws.send(data);
});
async function getRingdownData(userId, cachedStatusUpdates) {
const patientDeliveries = await models.PatientDelivery.findAll({
include: { all: true },
where: {
ParamedicUserId: userId,
currentDeliveryStatus: {
[Op.lt]: DeliveryStatus.RETURNED_TO_SERVICE,
},
},
});
const data = JSON.stringify({
ringdowns: await Promise.all(patientDeliveries.map((pd) => pd.toRingdownJSON())),
statusUpdates:
cachedStatusUpdates ||
(await Promise.all(
(await models.HospitalStatusUpdate.getLatestUpdatesWithAmbulanceCounts()).map((statusUpdate) => statusUpdate.toJSON())
)),
});
return data;
}
async function getStatusUpdateData(hospitalId) {
/// dispatch to all clients watching this hospital's ringdowns
const patientDeliveries = await models.PatientDelivery.findAll({
include: { all: true },
where: {
HospitalId: hospitalId,
currentDeliveryStatus: {
[Op.notIn]: [
DeliveryStatus.RETURNED_TO_SERVICE,
DeliveryStatus.CANCEL_ACKNOWLEDGED,
DeliveryStatus.REDIRECT_ACKNOWLEDGED,
DeliveryStatus.OFFLOADED_ACKNOWLEDGED,
],
},
},
});
const statusUpdate = await models.HospitalStatusUpdate.scope('latest').findOne({
where: {
HospitalId: hospitalId,
},
});
const data = JSON.stringify({
ringdowns: await Promise.all(patientDeliveries.map((pd) => pd.toRingdownJSON())),
statusUpdate: await statusUpdate.toJSON(),
});
return data;
}
async function dispatchStatusUpdate(hospitalId) {
// dispatch to all user clients
const cachedStatusUpdates = await Promise.all(
(await models.HospitalStatusUpdate.getLatestUpdatesWithAmbulanceCounts()).map((statusUpdate) => statusUpdate.toJSON())
);
const userPromises = [];
userServer.clients.forEach((ws) => {
userPromises.push(
getRingdownData(ws.info.userId, cachedStatusUpdates).then((data) => {
ws.send(data);
})
);
});
await Promise.all(userPromises);
// dispatch to all clients watching this hospital's ringdowns
const data = await getStatusUpdateData(hospitalId);
hospitalServer.clients.forEach((ws) => {
if (ws.info.hospitalId === hospitalId) {
ws.send(data);
}
});
}
async function dispatchRingdownUpdate(patientDeliveryId) {
// dispatch to all clients watching this user's ringdowns
const patientDelivery = await models.PatientDelivery.findByPk(patientDeliveryId);
const userId = patientDelivery.ParamedicUserId;
const data = await getRingdownData(userId);
userServer.clients.forEach((ws) => {
if (ws.info.userId === userId) {
ws.send(data);
}
});
// dispatch to all clients watching this hospital's ringdowns
await dispatchStatusUpdate(patientDelivery.HospitalId);
}
function getActiveHospitalUsers(hospitalId) {
const userIds = [];
hospitalServer.clients.forEach((ws) => {
if (ws.info.hospitalId === hospitalId) {
userIds.push(ws.info.userId);
}
});
return userIds;
}
function getActiveOrganizationUsers(organizationId) {
const userIds = [];
userServer.clients.forEach((ws) => {
if (ws.info.organizationId === organizationId) {
userIds.push(ws.info.userId);
}
});
return userIds;
}
function configure(server, app) {
server.on('upgrade', (req, socket, head) => {
app.sessionParser(req, {}, async () => {
const query = querystring.parse(url.parse(req.url).query);
/// ensure user logged in
if (req.session?.passport?.user) {
req.user = await models.User.findByPk(req.session.passport.user);
}
if (!req.user) {
socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
socket.destroy();
return;
}
/// connect based on pathname
const { pathname } = url.parse(req.url);
switch (pathname) {
case '/user':
userServer.handleUpgrade(req, socket, head, (ws) => {
userServer.emit('connection', ws, req);
});
break;
case '/hospital':
/// ensure valid hospital
if (query.id && query.id !== 'undefined') {
req.hospital = await models.Hospital.findByPk(query.id);
}
if (!req.hospital) {
socket.write('HTTP/1.1 403 Forbidden\r\n\r\n');
socket.destroy();
return;
}
hospitalServer.handleUpgrade(req, socket, head, (ws) => {
hospitalServer.emit('connection', ws, req);
});
break;
default:
socket.write('HTTP/1.1 403 Forbidden\r\n\r\n');
socket.destroy();
}
});
});
}
module.exports = {
configure,
dispatchRingdownUpdate,
dispatchStatusUpdate,
getActiveHospitalUsers,
getActiveOrganizationUsers,
};