-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.js
592 lines (422 loc) · 12.5 KB
/
app.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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
"use strict"
module.exports = (opts) => {
opts = opts || {
production: false,
static: null,
router: null,
authentication: []
};
/*****
Express and Socket.IO
*****/
const express = require('express');
const app = express();
const cors = require('cors');
const http = require('http').Server(app);
const io = require('socket.io')(http);
const fs = require('fs');
const cfenv = require('cfenv');
const appEnv = cfenv.getAppEnv();
const dbSetup = require('./lib/config.js').dbSetup;
if (opts.router) {
app.use(opts.router)
}
/*****
Bodyparser etc... for POST requests
*****/
const bodyParser = require('body-parser');
const bpJSON = bodyParser.json();
const bpUrlencoded = bodyParser.urlencoded({ extended: true});
/*****
Other stuff
*****/
const async = require('async');
const hash = require('./lib/hash.js');
const connected = require('./lib/connected.js')
const createSingleHash = hash.createSingleHash;
const db = require('./lib/db.js');
const cleanupFrequency = 60; //seconds
const url = require('url');
const isloggedin = require('./lib/isloggedin.js');
const log = require('./lib/metrics.js');
const path = require('path');
// app events
const events = require('events')
app.events = new events.EventEmitter();
// Use Passport to provide basic HTTP auth when locked down
const passport = require('passport');
passport.use(isloggedin.passportStrategy());
/*****
RethinkDB
*****/
const r = require("rethinkdb");
const rOpts = require('./lib/config.js').connection
/*****
Service Discovery
*****/
app.locals = {
discovery: ( process.env.ETCD_URL ? true : false ),
metrics: {
enabled: false,
name: null,
host: null
}
};
var registry = require('./lib/discovery.js')(app.locals);
/*****
API endpoints
*****/
// create a new authkey
// requires HTTP auth if lockdown=true
app.post('/authkey', isloggedin.auth, bpJSON, (req, res) => {
// make sure we have a body
if (typeof req.body !== "object" || req.body === null) {
return res.status(404).send({
success: false
})
}
// parse the values for hostname and key
let hostname = req.body.hostname || null
let key = req.body.key || null
if (hostname === null || key === null) {
return res.status(404).send({
success: false,
error: "You must supply both a hostname and a key"
})
}
// force http(s) protocol at the beginning if not present
// and make sure we have a hostname
if (hostname.match(/^https?:\/\//) === null) {
hostname = `http://${hostname}`
}
let h = url.parse(hostname);
if (h.hostname === null) {
return res.status(404).send({
success: false,
error: "You must supply a valid hostname"
})
}
// connect to DB and insert new record
r.connect(rOpts, (err, conn) => {
if (err) return res.status(404).send({
success: false,
error: "SNS: Failed to connect to database"
});
let data = {
hostname: h.hostname,
key: key
}
db.createAuthKey(conn, data, (err, cursor) => {
conn.close();
return res.send({
success: ( err ? false : true )
});
});
});
})
// delete authkey by unique id
// requires HTTP auth if lockdown=true
app.delete('/authkey/:id', isloggedin.auth, (req, res) => {
// connect to DB and delete record
r.connect(rOpts, (err, conn) => {
if (err) return res.status(404).send({
success: false,
error: "SNS: Failed to connect to database"
});
db.deleteAuthKey(conn, req.params.id, (err, cursor) => {
conn.close();
return res.send({
success: ( err ? false : true )
});
});
});
})
// get list of authkeys
// requires HTTP auth if lockdown=true
app.get('/authkeys', isloggedin.auth, (req, res) => {
r.connect(rOpts, (err, conn) => {
if (err) return res.status(404).send({
success: false,
error: "SNS: Failed to connect to database"
});
db.getAuthKeys(conn, (err, keys) => {
conn.close();
if (err) {
return res.status(404).send({
success: false,
error: err
});
}
return res.send({
success: true,
keys: keys
});
});
});
});
// POST a new notification via API
// requires valid API key
app.post('/:key/notification', cors(), bpJSON, (req, res) => {
if (typeof req.body !== "object" || req.body === null) {
return res.status(404).send({
success: false
})
}
let query = req.body.userQuery || {};
let data = req.body.notification || {};
// get our item in 'key-value' style from the query
let item = createSingleHash(query);
r.connect(rOpts, (err, conn) => {
if (err) return res.status(404).send({
success: false,
error: "SNS: Failed to connect to database"
});
db.authenticateLite(conn, req.params.key, (err, matches) => {
if (matches.length == 0) {
return res.status(404).send({
success: false,
error: "SNS: Failed to authenticate"
})
}
db.saveMessage(conn, item, data, (err, cursor) => {
conn.close();
return res.send({
success: ( err ? false : true )
});
});
});
});
});
// GET historical notifications via API
// requires valid API key
app.get('/:key/historical', cors(), (req, res) => {
r.connect(rOpts, (err, conn) => {
if (err) return res.status(404).send({
success: false,
error: "SNS: Failed to connect to database"
});
db.authenticateLite(conn, req.params.key, (err, matches) => {
if (matches.length == 0) {
return res.status(404).send({
success: false,
error: "SNS: Failed to authenticate"
});
}
db.getHistorical(conn, req.query, (err, messages) => {
if (err) return res.status(404).send({
success: false,
error: err
});
return res.send({
success: true,
notifications: messages.map(msg => msg.message)
});
});
});
});
});
// GET count of sent notifications via API
// requires valid API key
app.get('/:key/count', cors(), (req, res) => {
r.connect(rOpts, (err, conn) => {
if (err) return res.status(404).send({
success: false,
error: "SNS: Failed to connect to database"
});
db.authenticateLite(conn, req.params.key, (err, matches) => {
if (matches.length == 0) {
return res.status(404).send({
success: false,
error: "SNS: Failed to authenticate"
});
}
db.getMessageCount(conn, (err, count) => {
if (err) return res.status(404).send({
success: false,
error: err
})
res.send({
success: true,
count: count
});
});
});
});
});
/*****
IO Stuff
*****/
io.on('connect', socket => {
console.log(`${socket.id} connected...`)
connected.push(socket.id);
log(app.locals.metrics, { action: "connected", id: encodeURIComponent(socket.id) })
// flag user as being updated when we receive a heartbeat
// this will help us tidy up the users table later
socket.conn.on('heartbeat', function() {
r.connect(rOpts, (err, conn) => {
if (err) return;
db.updateHeartbeat(conn, socket.id, () => {
conn.close()
})
});
});
// Client supplies descriptive data about themselves (userData)
// can also supply a query that describes other users they care about (userQuery)
socket.on('myData', data => {
// make sure data is an object
if (typeof data === "undefined" || data === null) {
data = {}
}
// and that we have some user data
if (data.userData === null || typeof data.userData !== "object" || Array.isArray(data.userData)) {
data.userData = {};
}
data.userData._socket_id = socket.id
// authenticate, and if fine
// stash them in the DB
r.connect(rOpts, (err, conn) => {
if (err) return;
let actions = {};
actions.authenticate = (callback) => {
db.authenticate(conn, data.authentication || null, callback)
}
// insert the user
actions.insertUser = (callback) => {
db.insertUser(conn, data, socket.id, callback)
}
// find who else is connected that we care about
actions.fetchConnected = (callback) => {
db.fetchConnected(conn, data, socket.id, callback)
}
async.series(actions, (err, results) => {
conn.close();
if (err) {
socket.emit('authenticationFail')
socket.disconnect()
return;
}
// send back a list of currently connected users that match the userQuery
if (typeof results.fetchConnected == "object" && results.fetchConnected.length >= 0) {
socket.emit('currentUsers', results.fetchConnected)
}
})
})
})
// when the socket disconnects, remove by socket ID
socket.on('disconnect', () => {
console.log(`${socket.id} disconnected...`);
connected.remove(socket.id);
log(app.locals.metrics, { action: "disconnected", id: encodeURIComponent(socket.id) })
r.connect(rOpts, (err, conn) => {
db.deleteUser(conn, socket.id, (err, success) => {
conn.close();
})
})
})
// when the client sends a message
// determine the Socket IDs to send it to
// store this data in the messages table
socket.on('notification', msg => {
let query = msg.query;
let data = msg.data;
// get our item in 'key-value' style from the query
let item = createSingleHash(query);
r.connect(rOpts, (err, conn) => {
if (err) return;
db.saveMessage(conn, item, data, (err, cursor) => {
conn.close();
return;
})
})
})
});
/*****
FRONT END
*****/
if (opts.production === false) {
app.get('/chat', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'demo', 'chat', 'chat.html'));
});
app.get('/soccer', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'demo', 'soccer', 'soccer.html'));
});
app.get('/soccer/admin', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'demo', 'soccer', 'admin.html'));
});
}
app.get('/sns-client.js', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'client.js'));
});
// serve static files from /public if not otherwise provided in opts
if (opts.static === null) {
app.use(express.static(path.join(__dirname, 'public')));
}
else {
app.use(express.static(opts.static));
}
// attempt to set up the DB before running the app.
dbSetup(opts.authentication, (err) => {
// if the DB failed to setup, then exit.
if (err) {
console.log(err);
process.exit(0);
}
/*****
RethinkDB changefeeds
*****/
r.connect(rOpts, (err, conn) => {
if (err) return;
const msgStream = db.messageStream(conn);
msgStream.on('notification', (data) => {
if (!connected.exists(data.id)) return false;
io.to(data.id).emit('notification', data.msg);
log(app.locals.metrics, { action: "notification", id: encodeURIComponent(data.id), data: JSON.stringify(data.msg) })
})
msgStream.on('notificationPing', () => {
io.emit('notificationPing');
})
const userStream = db.userStream(conn);
userStream.on('connectingUser', (user) => {
db.sendConnected(conn, user, (err, users) => {
// send this clients userData to any connected user whose userQuery matches this clients userData
if (typeof users == "object" && users.length >= 0) {
users.forEach(id => {
if (!connected.exists(id)) return false;
io.to(id).emit("connectedUser", user.userData)
log(app.locals.metrics, { action: "connectionNotification", id: encodeURIComponent(id) })
})
}
})
})
userStream.on('disconnectingUser', (user) => {
db.sendDisconnected(conn, user, (err, users) => {
// send this clients userData to any connected user whose userQuery matches this clients userData
if (typeof users == "object" && users.length >= 0) {
users.forEach(id => {
if (!connected.exists(id)) return false;
io.to(id).emit("disconnectedUser", user.userData)
log(app.locals.metrics, { action: "disconnectionNotification", id: encodeURIComponent(id) })
})
}
})
})
/*****
Tidy up old users
(re-using the changefeed connection)
****/
db.removeOldUsers(conn, cleanupFrequency);
setInterval(() => {
db.removeOldUsers(conn, cleanupFrequency);
}, (cleanupFrequency * 1000))
})
/*****
Listening
*****/
http.listen(appEnv.port, ( appEnv.bind == "localhost" ? null : appEnv.bind ), () => {
console.log(`listening on ${appEnv.url}`);
app.events.emit('started', appEnv.url)
});
});
require("cf-deployment-tracker-client").track();
return app;
}