-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
87 lines (77 loc) · 2.46 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
// Configure Raygun exceptions
if(process.env.RAYGUN_API_KEY) {
var raygun = require('raygun');
var raygunClient = new raygun.Client().init({ apiKey: process.env.RAYGUN_API_KEY });
}
var domain = require('domain').create();
domain.on('error', function(err){
if(typeof(raygunClient) != 'undefined'){
raygunClient.send(err, {}, function () {
console.log(err);
process.exit();
});
} else {
throw err
}
});
domain.run(function(){
process.env.NEW_RELIC_APP_NAME && require('newrelic');
var port = process.env.PORT || 9000
var http = require('http').Server();
var io = require('socket.io')(http);
if(process.env.REDIS_URL) {
var redis = require("redis").createClient({url: process.env.REDIS_URL});
}
else {
var redis = require("redis").createClient({
host: '127.0.0.1',
port: 6379 });
}
// Returns a socket object matching the specified socket id.
function socketFromId(socketId) {
return io.sockets.sockets.filter(
function(socket){ return socket.id == socketId; }
)[0];
}
// TODO: This is only for debugging. No need to do anything on connection.
io.on('connection', function(socket){
console.log('Opened new socket: ' + socket.id);
});
redisPublishCallbacks = {
'LiveUpdates': function(msg){
try {
parsedMsg = JSON.parse(msg);
room = parsedMsg["room"];
data = parsedMsg["data"];
io.to(room).emit(room, data);
} catch (err) { console.log(err) }
},
// http://socket.io/docs/rooms-and-namespaces/#
'RoomSubscriberAdd': function(msg) {
try {
parsedMsg = JSON.parse(msg);
socketId = parsedMsg["socket_id"];
if(socket = socketFromId(socketId)) {
if(parsedMsg["rooms"]) {
parsedMsg["rooms"].forEach(function(room) {
socket.join(room);
})
}
}
} catch (err) { console.log(err) }
}
}
// We subscribe to 2 different channels on Redis (Pub/Sub)
// Whenever we receive a message from redis we call the relevant callback
// for the channel.
redis.on("message", function(channel, message) {
if(redisPublishCallbacks[channel]) {
redisPublishCallbacks[channel](message);
}
});
redis.subscribe("LiveUpdates"); // Where changes to be pushed to sockets are sent
redis.subscribe("RoomSubscriberAdd"); // Where new subscribers for rooms are sent
http.listen(port, function(){
console.log('listening on *:' + port);
});
});