-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
364 lines (274 loc) · 8.43 KB
/
server.js
File metadata and controls
364 lines (274 loc) · 8.43 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
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
356
357
358
359
360
361
362
363
364
require('log-timestamp');
var http = require('https');
var config = require('./config');
var Firebase = require('firebase');
var tasksRef = new Firebase(config.TasksFirebaseURL);
var queuesRef = new Firebase(config.QueuesFirebaseURL);
var usersRef = new Firebase(config.UsersFirebaseURL);
var managedQueues = [];
var delayedServices = [];
function taskSendSMS(number, message)
{
var options = {
host: 'api.clockworksms.com',
path: '/http/send.aspx?key=' + config.ClockworkSMSKey + '&to=' + number + '&content=' + message
};
callback = function(response) {
var str = '';
//another chunk of data has been recieved, so append it to `str`
response.on('data', function (chunk) {
str += chunk;
});
//the whole response has been recieved, so we just print it out here
response.on('end', function () {
console.log(str);
});
}
http.request(options, callback).end();
}
function setStatus(userRef, state)
{
userRef.child('status').set(state);
}
function getUserRef(userId)
{
return usersRef.child(userId).ref();
}
function sendSMS(userRef, message)
{
userRef.once('value', function(sendSMSSnapshot) {
user = sendSMSSnapshot.val();
if(user.mobile && !user.mobile.indexOf("4455") == 0)
{
addTask('sms', { mobile: user.mobile, message: encodeURIComponent(message) });
}
else
{
console.log("User " + user.fullName + " has no mobile or has a test number so we won't try sending an SMS");
}
});
}
function addTask(type, payload)
{
//console.dir(type);
//console.dir(payload);
tasksRef.push({ task: type, payload: payload });
}
function handleQueuedUser(handleUserSnapShot)
{
var item = handleUserSnapShot.val();
//Get parent queueId
var parentQueue = handleUserSnapShot.ref().parent().ref().parent();
parentQueue.child('messages').ref().once('value', function(messagesSnapshot) {
messages = messagesSnapshot.val();
switch(item.status)
{
case 'joined':
sendSMS(getUserRef(item.userId), messages.joined);
setStatus(handleUserSnapShot.ref(), 'waiting');
break;
case 'servicing':
if(!item.processedServicing)
{
sendSMS(getUserRef(item.userId), messages.servicing);
parentQueue.ref().once('value', function(queueSnapshot) {
if(queueSnapshot.val().type == 'automated')
{
console.log(item.processed)
console.log("Scheduling delayed Service");
var t = new Date();
t.setSeconds(t.getSeconds() + queueSnapshot.val().serviceTime);
//This was an attempt to fix the annoying GMT/BST bug at 1:30am the first time round. It failed.
//var t = new Date(t.valueOf() - t.getTimezoneOffset() * 60000);
payload = { queue: queueSnapshot.name(),
user: item.userId,
dequeueTime: t.toISOString()
};
addTask('delayedService', payload);
handleUserSnapShot.ref().child('processedServicing').set(true);
}
});
}
break;
case 'serviced':
sendSMS(getUserRef(item.userId), messages.serviced);
handleUserSnapShot.ref().remove();
break;
case 'holding':
if(!item.processedHold)
{
sendSMS(getUserRef(item.userId), messages.holding);
handleUserSnapShot.ref().child('processedHold').set(true);
}
break;
case 'waiting':
//If moving into waiting clean up any state specific locks
if(item.processedHold)
{
handleUserSnapShot.ref().child('processedHold').ref().remove();
}
if(item.processedServicing)
{
handleUserSnapShot.ref().child('processedServicing').ref().remove();
}
break;
}
});
}
function handleUser(handleUserSnapShot)
{
user = handleUserSnapShot.val();
if(user.fullName == 'Anonymous')
{
if(!user.registrationTextSent)
{
console.log("Anonymous user detected. Sending registration text");
sendSMS(handleUserSnapShot.ref(), "Thanks for using qcue.me. Unfortunately we don't know who you are. Reply with NAME followed by your name to register.");
handleUserSnapShot.ref().child('registrationTextSent').set(true);
}
}
if(user.status == 'registered')
{
console.log(user.fullName + 'has now registered. Sending confirmation message.');
sendSMS(handleUserSnapShot.ref(), "Thanks for registering for qcue.me. We won't bother you anymore with such trivial questions.");
handleUserSnapShot.ref().child('status').remove();
}
}
console.log("Worker initialising")
tasksRef.on('child_added', function(snapshot) {
//console.log(snapshot)
item = snapshot.val();
var processed = item.processed, task = item.task, payload = item.payload;
if(!processed)
{
switch(task)
{
case 'sms':
console.log('Received SMS task. Number: ' + payload.mobile);
taskSendSMS(payload.mobile, payload.message)
snapshot.ref().remove();
break;
case 'delayedService':
console.log('Loading delayedService into memory for processing when required');
delayedServices.push(snapshot);
break;
default:
console.log('Unknown task: ' + task);
break;
}
}
});
queuesRef.on('child_added', function(snapshot) {
item = snapshot.val();
if(item.type == 'automated')
{
console.log('Found automated queue ' + item.name + '. Monitoring.')
managedQueues.push({queue: snapshot.ref(), timer: item.gap, lastChecked: new Date()});
}
//Add event to queue to monitor for changes to users in queue.
console.log('Monitoring for user changes for queue ' + item.name + '.')
users = snapshot.child('users');
users.ref().on('child_changed', function(snapshot) {
item = snapshot.val();
handleQueuedUser(snapshot);
});
users.ref().on('child_added', function(snapshot) {
item = snapshot.val();
handleQueuedUser(snapshot);
});
});
usersRef.on('child_added', function(childSnapshot) {
handleUser(childSnapshot);
});
usersRef.on('child_changed', function(childSnapshot) {
handleUser(childSnapshot);
});
setInterval(function() {
//console.log("Checking automated queues")
//PROCESS QUEUES
var length = managedQueues.length,
element = null;
for (var i = 0; i < length; i++)
{
element = managedQueues[i];
//console.log(element);
var now = new Date();
var diffTime = now.getTime() - element.lastChecked.getTime();
//console.log(diffTime);
if(diffTime > element.timer * 1000)
{
//Mark last checked as now
element.lastChecked = now;
//Get the item from firebase
element.queue.once('value', function(snapshot) {
processItem = snapshot.val();
startDate = new Date(processItem.queueStart);
if(startDate < new Date())
{
console.log("Processing queue: " + processItem.name);
if(processItem.users)
{
snapshot.child('users').ref().once('value', function(usersSnapshot){
var didDequeue = false;
usersSnapshot.forEach(function(userSnapshot){
if(!didDequeue)
{
queuedUser = userSnapshot.val();
if(queuedUser.status == 'waiting')
{
console.log("Servicing " + queuedUser.userId)
setStatus(userSnapshot.ref(), 'servicing');
didDequeue = true;
}
}
});
})
}
console.log("Finished processing queue: " + processItem.name);
}
else
{
console.log("Queue not started: " + processItem.name);
}
//Update local timer cache
element.timer = processItem.gap;
});
}
}
//PROCESS DELAYEDSERVICE
length = delayedServices.length,
element = null;
//console.log(delayedServices.length)
for (var i = 0; i < length; i++)
{
//console.log(i)
//console.log(delayedServices.length)
element = delayedServices[i];
//console.dir(element)
dequeue = new Date(element.val().payload.dequeueTime)
//console.log(dequeue)
if(dequeue < new Date())
{
userItem = queuesRef.child(element.val().payload.queue).child('users').ref().once('value', function(delServiceSnapshot){
delServiceSnapshot.forEach(function(userItemSnapshot){
userItem = userItemSnapshot.val();
if(userItem.userId == element.val().payload.user)
{
console.log('Servicing as a result of delayed service');
setStatus(userItemSnapshot.ref(), 'serviced');
}
});
//console.dir(delayedServices)
//We process these outside the loop in order to quietly tidyup incase duplicates get added
//Delete from firebase
element.ref().remove();
//Remove from array
delayedServices.splice(i, 1);
//We need to do this to compensate for the removal of an item from the queue. Bit hacky.
i = i - 1;
length = delayedServices.length;
});
}
}
}, 1000)
console.log("Worker initialised");