Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
364 lines (325 loc) · 14.3 KB
/
Copy pathserver.js
File metadata and controls
364 lines (325 loc) · 14.3 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
var http = require("http"),
util = require("util"),
fs = require("fs"),
sys = require("sys"),
parseUrl = require('url').parse,
io = require("socket.io"),
redis = require("redis"),
und = require("underscore");
/*
* Redis configuration
*/
var redisPort,
redisHost,
redisPwd,
redisUri,
redisDb = process.env.REDIS_DB || 0;
if (process.env.REDISTOGO_URL) {
redisUri = parseUrl(process.env.REDISTOGO_URL);
redisPwd = redisUri.auth.split(':')[1];
redisHost = redisUri.hostname;
redisPort = redisUri.port;
} else {
redisPort = process.env.REDIS_PORT;
redisHost = process.env.REDIS_HOST;
}
var redisClient = redis.createClient(redisPort, redisHost),
subscribeRedisClient = redis.createClient(redisPort, redisHost);
redisClient.on("error", function (err, res) {
util.log(err);
});
redisClient.on("connect", function (err, res) {
util.log("Connected!");
})
if (redisPwd) {
redisClient.auth(redisPwd);
subscribeRedisClient.auth(redisPwd);
}
/*
* Server port
*/
var serverPort = process.env.PORT || 8080;
/*
* Send 404 Not Found
*/
var send404 = function (res) {
res.writeHead(404, {"Content-Type": "text/plain"});
res.end("404 Not Found");
};
/*
* Return first (probably random) key
* Used to retrieve root key from deserialized JSON messages
*/
var firstKey = function (obj) {
for (var k in obj) {
if (obj.hasOwnProperty(k)) {
return k;
}
}
};
var Group = function (id, token) {
this.userAuthenticationKey = "group:" + id + ":token:" + token;
this.sessionsKey = "group:" + id + ":sessions";
this.channel = "group:" + id;
};
Group.prototype.authenticationSuccessedMessage = { type: "group.authentication", status: "OK" };
Group.prototype.authenticationFailedMessage = { type: "group.authentication", status: "error", text: "Invalid ID or token" };
var ChatActivity = function (id, token) {
this.userAuthenticationKey = "activity:" + id + ":token:" + token;
this.sessionsKey = "activity:" + id + ":sessions";
this.channel = "activity:" + id;
this.userChannel = "activity:" + id + ":user:";
}
ChatActivity.prototype.authenticationSuccessedMessage = { type: "activity.authenticate", status: "OK" };
ChatActivity.prototype.authenticationFailedMessage = { type: "activity.authenticate", status: "error", text: "Invalid ID or token" };
var Chat = function (id, token) {
this.userAuthenticationKey = "chat:" + id + ":token:" + token;
this.sessionsKey = "chat:" + id + ":sessions";
this.channel = "chat:" + id;
};
Chat.prototype.authenticationSuccessedMessage = { type: "chat.authentication", status: "OK" };
Chat.prototype.authenticationFailedMessage = { type: "chat.authentication", status: "error", text: "Invalid ID or token" };
var server = http.createServer(function (req, res) {
send404(res);
});
var socket = io.listen(server);
server.listen(serverPort);
util.log("Server started on port " + serverPort);
var PGS = {
initialize: function () {
PGS.username = process.env.PGS_USERNAME || "node";
PGS.password = process.env.PGS_PASSWORD || "secret";
PGS.host = process.env.PGS_HOST || "localhost";
PGS.port = process.env.PGS_PORT || 3000;
},
auth_header: function () {
return "Basic " + new Buffer(PGS.username + ":" + PGS.password).toString("base64");
},
node_supervision_member_path: function (supervisionId, memberId) {
return "/node/supervisions/" + supervisionId + "/members/" + memberId;
},
request: function (path, method) {
var options = {
host: PGS.host,
port: PGS.port,
path: path,
method: method,
headers: {"Content-Type": "application/json", "Accept": "application/json", "Authorization": PGS.auth_header()}
},
req = http.request(options, function (res) {
res.setEncoding('utf8');
});
req.on('error', function (e) {
console.log('problem with request: ' + e.message);
});
req.end();
}
};
/*
* Call callback for each session from Redis hash
*/
var eachSession = function (key, callback) {
var sessionsKey = key + ":sessions";
redisClient.hgetall(sessionsKey, function (err, replies) {
und.each(replies, function(sessionId, userId) {
var client = socket.clients[sessionId];
if (client) {
callback.call(client, client);
} else {
redisClient.hdel(sessionsKey, userId);
}
});
});
};
var initializeClientConnections = function () {
var supervisionStatusTimeout;
socket.on('connection', function (client) {
client.on("message", function (message) {
util.log("message:" + message);
if (message.type.search(/^activity\./) === 0) {
if (message.type === "activity.authenticate") {
var chatId = message.data.chatId,
token = message.data.token,
chatActivity = new ChatActivity(chatId, token);
redisClient.get(chatActivity.userAuthenticationKey, function (err, userId) {
if (userId) {
util.log("[activity] User: " + userId + " authenticated for chat: " + chatId + " sessionId: " + client.sessionId);
client.send(chatActivity.authenticationSuccessedMessage);
redisClient.hset(chatActivity.sessionsKey, userId, client.sessionId);
}
});
}
if (message.type === "activity.ping") {
var chatId = message.data.chatId,
token = message.data.token,
status = message.data.status,
userId = message.data.userId,
chatActivity = new ChatActivity(chatId, token);
timestamp = parseInt(Number(new Date) /1000);
redisClient.publish(chatActivity.channel, JSON.stringify({message: {status: status, id: userId, timestamp: timestamp} }) );
redisClient.setex(chatActivity.userChannel + userId, 60, status);
}
}
if (message.type.search(/^group\./) === 0) {
if (message.type === "group.authenticate") {
var groupId = message.data.groupId,
token = message.data.token,
group = new Group(groupId, token);
redisClient.get(group.userAuthenticationKey, function (err, userId) {
if (userId) {
util.log("[group] User:" + userId + " authenticated for group:" + groupId + " sessionId:" + client.sessionId);
client.send(group.authenticationSuccessedMessage);
redisClient.hset(group.sessionsKey, userId, client.sessionId);
}
client.on("disconnect", function () {
// Remove user from chat session after 30 seconds
redisClient.hdel(group.sessionsKey, userId);
});
});
}
}
/**
* CHAT
* - authenticate
* message format: { type: "chat.authenticate", chatRoomId: <id>, userId: <userId>, token: <token> }
*/
if (message.type.search(/^chat\./) === 0) {
// on authenticate
if (message.type === "chat.authenticate") {
var chatRoomId = message.data.chatRoomId,
token = message.data.token,
chat = new Chat(chatRoomId, token);
redisClient.get(chat.userAuthenticationKey, function (err, userId) {
if (userId) {
util.log("[chat] User:" + userId + " authenticated for chat:" + chatRoomId + " sessionId:" + client.sessionId);
client.send(chat.authenticationSuccessedMessage);
// Hash of chat session, contains: {userId: sessionId}
redisClient.hset(chat.sessionsKey, userId, client.sessionId);
redisClient.hkeys(chat.sessionsKey, function (err, resp) {
redisClient.publish(chat.channel, JSON.stringify({chat_presence: {user_ids: resp, user_id: userId, status: "enter"}}));
});
client.on("disconnect", function () {
// Remove user from chat session after 30 seconds
redisClient.hdel(chat.sessionsKey, userId);
setTimeout(function () {
redisClient.hkeys(chat.sessionsKey, function (err, resp) {
if (!und.include(resp, userId)) {
redisClient.publish(chat.channel, JSON.stringify({chat_presence: {user_ids: resp, user_id: userId, status: "exit"}}));
}
});
}, 30000);
});
} else {
util.log("[chat] Invalid token:" + token + " for chat:" + chatRoomId);
client.send(chat.authenticationFailedMessage);
}
});
}
}
/*
* SUPERVISION SESSION
* - authenticate
* message format: { type: "supervision.authenticate", supervisionId: <id>, userId: <userId>, token: <token> }
*/
if (message.type.search(/^supervision\./) === 0) {
var supervisionId = message.data.supervisionId;
// on authenticate
if (message.type === "supervision.authenticate") {
var userId = String(message.data.userId),
token = message.data.token,
userAuthenticationKey = "supervision:" + supervisionId + ":users:" + userId + ":token:" + token,
supervisionSessionsKey = "supervision:" + supervisionId + ":sessions";
redisClient.exists(userAuthenticationKey, function (err, resp) {
if (resp) {
console.log("User authenticated for supervision: " + userId + " sessionId: " + client.sessionId);
client.send({ type: "supervision.authentication", status: "OK" });
redisClient.hset(supervisionSessionsKey, userId, client.sessionId);
client.on("disconnect", function () {
redisClient.hdel("supervision:" + supervisionId + ":sessions", userId);
// remove member from supervision after 30 seconds
supervisionStatusTimeout = setTimeout(function () {
redisClient.hkeys(supervisionSessionsKey, function (err, resp) {
if (!und.include(resp, userId)) {
PGS.request(PGS.node_supervision_member_path(supervisionId, userId), "DELETE");
}
});
}, 30000);
});
} else {
console.log("User invalid for supervision: " + userId);
client.send({ type: "supervision.authentication", status: "error", text: "Invalid id or token" });
}
});
} else if (message.type === "supervision.member_idle_status") {
if (message.data.status === "away") {
PGS.request(PGS.node_supervision_member_path(supervisionId, message.data.userId), "DELETE");
// hack for not sending second request on client disconnect
// TODO: find a better way to do this
setTimeout(function() {
clearTimeout(supervisionStatusTimeout);
}, 2000);
}
redisClient.publish("supervision:" + supervisionId, JSON.stringify({idle_status_changed: message.data}));
}
}
});
});
};
var subscribeToChannels = function () {
subscribeRedisClient.on("pmessage", function (pattern, channel, pmessage) {
var decodedMessage = JSON.parse(pmessage),
rootKey = firstKey(decodedMessage),
type;
switch (pattern) {
case "supervision:*":
type = "supervision";
break;
case "activity:*":
type = "activity";
break;
case "chat:*":
type = "chat";
break;
case "group:*":
type = "group";
break;
default:
util.log("Unknown message type: " + rootKey);
return;
}
decodedMessage.type = type + "." + rootKey;
util.log("[" + type + "] pmessage: " + decodedMessage.type);
eachSession(channel, function (client) {
util.log("[" + type + "] Sending message to client " + client.sessionId);
client.send(decodedMessage);
});
});
subscribeRedisClient.on("error", function (foo, bar) {
util.log("\n\n Error !! \n\n");
util.log(foo);
});
subscribeRedisClient.psubscribe("supervision:*");
subscribeRedisClient.psubscribe("chat:*");
subscribeRedisClient.psubscribe("activity:*");
subscribeRedisClient.psubscribe("group:*");
};
subscribeToChannels();
// Only select DB for redisClient, as subscribeRedisClient can work without selecting database,
// pub/sub works across db's
redisClient.select(redisDb, function (err, resp) {
if (!err) {
util.log("Initializing client connection support");
initializeClientConnections();
} else {
util.log("[ERROR] Could not select redisDb: " + redisDb + ", exiting");
process.exit(-1);
}
});
var pingRedisClient = function () {
redisClient.ping();
};
setInterval(pingRedisClient, 10000);
/*
* Setup configuration to connect to rails application
*/
PGS.initialize();