-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
352 lines (303 loc) · 9.01 KB
/
index.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
// content of index.js
const http = require('http');
const port = process.env.PORT || 3000;
const responder = require("./responder.js");
const idGen = require("./idgenerator.js");
const uuidv4 = require('uuid/v4');
const Dotenv = require('dotenv');
Dotenv.config({
silent: true
});
const mapsClient = require('@google/maps').createClient({
key: process.env.MAPS_KEY
});
const twilioClient = require('twilio')(
process.env.TWILIO_SID,
process.env.TWILIO_TOKEN
);
const stageLatLng = 1;
const stageAddress = 2;
const stageEnded = -1;
// If expirationTime is set to -1, requests will never expire
// Otherwise, a good value is ten minutes
const minute = 60 * 1000;
const expirationTime = -1;
const reasonExpired = "expired."
const reasonDispatcher = "Your emergency was successfully handled by the dispatcher."
const reasonCaller = "was ended successfully by its caller.";
const requestHandler = (request, response) => {
if (request.url.toString() == "/") {
response.end("Wecome to the server of the 2017-doi-app!");
}
callback = callbackCreator(response, false)
var result = request.url.toString().split("/");
if (result.length != 3) {
callback(false, "Page not found.", 404);
return;
}
URL_GET = buildURL_GET(request.url.toString())
switch (result[1]) {
case "start-call":
prepLatLng(URL_GET["DeviceID"], URL_GET["LatLng"], URL_GET["From"], false, callback);
break;
case "update-latlng":
prepUpdateLatLng(URL_GET["DeviceID"], URL_GET["LatLng"], callback);
break;
case "update-description":
prepUpdateDescription(URL_GET["DeviceID"], URL_GET["Description"], callback);
break;
case "end-emergency":
var reason;
if (URL_GET["DeviceID"]) {
reason = reasonCaller;
} else {
reason = reasonDispatcher;
}
endEmergency(URL_GET["DeviceID"], URL_GET["EmergencyID"], reason, callback);
break;
case "dispatch-status":
getDispatch(URL_GET["DeviceID"], URL_GET["EmergencyID"], response, callback);
break;
case "fetch-info":
fetchAddress(URL_GET["DeviceID"], URL_GET["EmergencyID"], response, callback);
break;
case "sms":
smsHandler(response, URL_GET["Body"], URL_GET["From"]);
break;
default:
callback(false, "Page not found.", 404);
break;
}
}
function smsHandler(response, body, phoneNumber) {
result = body.split("\n");
callback = callbackCreator(response, true);
const firstLine = result[0].split("+");
if (strip(phoneNumber) == strip(process.env.DISPATCH_NUMBER) && firstLine.length >= 2) {
switch (firstLine[0].toLowerCase()) {
case "yes":
responder.acceptDispatch(firstLine[1].toUpperCase(), true, callback);
break;
case "no":
responder.acceptDispatch(firstLine[1].toUpperCase(), false, callback);
break;
default:
callback(false, "Request not found.", 404);
break;
}
return;
}
switch (result[0]) {
case "start-call":
prepLatLng(result[1], result[2], phoneNumber, true, callback);
break;
case "update-latlng":
prepUpdateLatLng(result[1], result[2], callback);
break;
case "end-emergency":
// Ending by sms is only supported on the caller side
endEmergency(result[1], undefined, reasonCaller, callback);
break;
default:
callback(false, "Request not found.", 404);
break;
}
}
function prepLatLng(deviceID, latLng, phoneNumber, isSMS, callback) {
if (!deviceID || !latLng || !phoneNumber) {
callback(false, "Invalid request.", 400);
return false;
}
var emergencyID;
try {
emergencyID = idGen.makeByDevice(deviceID);
idGen.setStageByEmergency(emergencyID, stageLatLng);
} catch (e) {
console.error(e);
callback(false, "Internal server error.", 500);
return false;
}
responder.prepareDispatch(emergencyID, phoneNumber, isSMS);
responder.handleLatLng(emergencyID, latLng, callback);
// As mentioned above, just change expiration time to -1 to never expire emergencies
if (expirationTime == -1) {
console.log("Not expiring addresses.");
return true;
}
setTimeout(function() {
endEmergency(deviceID, emergencyID, phoneNumber, reasonExpired, function(s, t, c) {
console.log("Emergency " + emergencyID + " timed out.");
console.log("Result of timeout was: ", s, t, c);
});
}, expirationTime);
return true;
}
function prepUpdateLatLng(deviceID, latLng, callback) {
if (!deviceID || !latLng) {
callback(false, "Invalid request.", 400);
return;
}
const emergencyID = tryGetEmergencyID(deviceID, callback);
if (!emergencyID) {
return;
}
try {
idGen.setStageByEmergency(emergencyID, stageAddress);
} catch (e) {
console.error(e);
callback(false, "Internal server error.", 500);
return;
}
responder.updateLatLng(emergencyID, latLng, callback);
}
function prepUpdateDescription(deviceID, description, callback) {
if (!deviceID || !description) {
callback(false, "Invalid request.", 400);
return;
}
const emergencyID = tryGetEmergencyID(deviceID, callback);
if (!emergencyID) {
return;
}
responder.updateDescription(emergencyID, description, callback);
}
function getDispatch(deviceID, emergencyID, response, callback) {
if (!deviceID && !emergencyID) {
callback(false, "Invalid request.", 400);
return;
}
if (!emergencyID) {
try {
emergencyID = idGen.getEmergencyFromArchive(deviceID);
} catch (e) {
console.error(e);
callback(false, "Could not find emergency.", 404);
return;
}
}
response.end(responder.getDispatchStatus(emergencyID));
}
function fetchAddress(deviceID, emergencyID, response, callback) {
if (!deviceID && !emergencyID) {
callback(false, "Invalid request.", 400);
return;
}
if (!emergencyID) {
emergencyID = tryGetEmergencyID(deviceID, callback);
if (!emergencyID) {
// We were unable to get the emergencyID from our storage and it was not passed in
// So we must stop
return;
}
}
json = responder.getLocationJSON(emergencyID);
if (!json) {
callback(false, "Location not found.", 404);
return;
}
response.setHeader('Content-Type', 'application/json');
response.end(json);
}
function endEmergency(deviceID, emergencyID, reason, callback) {
if (!deviceID && !emergencyID) {
callback(false, "Invalid request.", 400);
return;
}
if (!emergencyID) {
emergencyID = tryGetEmergencyID(deviceID, callback);
if (!emergencyID) {
// We were unable to get the emergencyID from our storage and it was not passed in
// So we must stop
return;
}
}
wasDispatcher = reason == reasonDispatcher;
if (!wasDispatcher) {
// We need to suffix the reason we send to dispatcher with the emergency ID.
reason = "Emergency " + emergencyID + " " + reason;
}
try {
idGen.endByEmergency(emergencyID);
responder.expireLocation(emergencyID, wasDispatcher, reason, callback);
} catch (e) {
console.error(e);
callback(false, "Internal server error.", 500);
return;
}
}
function tryGetEmergencyID(deviceID, callback) {
var emergencyID;
try {
emergencyID = idGen.getEmergencyByDevice(deviceID);
} catch (e) {
console.error(e);
callback(false, "Could not find emergency.", 404);
}
return emergencyID;
}
function callbackCreator(response, isSMS) {
var called = false;
var callback;
if (isSMS) {
callback = (success, text, code) => {
if (called) {
console.error("Calling callback more than once");
return;
}
called = true;
response.setHeader('Content-Type', 'text/xml');
if (success) {
response.end("<Response></Response>");
return;
}
response.end("<Response><Message>Error: " + code + ". " + text +
" Failed to handle your request.</Message></Response>");
}
} else {
callback = (success, text, code) => {
if (called) {
console.error("Calling callback more than once");
return;
}
called = true;
response.writeHead(code, text, {
'Content-Length': Buffer.byteLength(text),
'Content-Type': 'text/plain'
});
response.end(text);
}
}
return callback;
}
function buildURL_GET(urlString) {
var URL_GET = {};
if (urlString.indexOf('?') == -1) {
return URL_GET;
}
var query = urlString
.toString()
// get the query string
.replace(/^.*?\?/, '')
// and remove any existing hash string (thanks, @vrijdenker on SE)
.replace(/#.*$/, '')
.split('&');
for (var i = 0, l = query.length; i < l; i++) {
var aux = decodeURIComponent(query[i]).split('=');
URL_GET[aux[0]] = aux[1];
}
return URL_GET;
}
function strip(phoneNumber) {
return phoneNumber.replace(/ /g, "")
.replace(/\(/g, "")
.replace(/\)/g, "")
.replace(/\-/g, "")
.replace(/\+/g, "");
}
const server = http.createServer(requestHandler);
server.listen(port, (err) => {
if (err) {
return console.log('something bad happened', err);
}
console.log(`server is listening on ${port}`);
})