-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
78 lines (65 loc) · 2.16 KB
/
app.js
File metadata and controls
78 lines (65 loc) · 2.16 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
/* Requires */
var s = require('underscore.string');
var express = require('express');
var config = require('./config.json');
var utils = require('./lib/utils.js');
var path = require('path');
var pack = require('./package.json');
var log = require('./lib/log.js');
var port = 3000;
/* Express */
var app = express();
app.set('port', port);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
/* Variables */
var clients = [];
var messages = [];
/* Routes */
app.use(config.url, express.static(path.join(__dirname, 'public')));
app.get(config.url, function (req, res) {
res.render('index', {version:pack.version});
});
var http = require('http').Server(app);
var io = require('socket.io')(http);
io.use(function(socket, next){
userInformation = JSON.parse(socket.handshake.query.userInfo);
if (!userInformation.uid) {
next(new Error('Authentication error'));
}
clients[userInformation.uid] = userInformation;
return next();
});
io.on('connection', function(socket){
socket.on('newmessage', function(content){
msg = JSON.parse(content);
msg.msg = s.escapeHTML(msg.msg);
msg.user.id = s.escapeHTML(msg.user.id);
msg.user.channelId = s.escapeHTML(msg.user.channelId);
channelId = msg.user.channelId;
channelName = 'message' + channelId;
io.emit(channelName, JSON.stringify({
'msg': msg.msg,
'user': clients[msg.user.uid]
}));
// inti empty channel
if (!messages[channelId]) {
messages[channelId] = [];
}
messages[channelId].push([msg]);
});
socket.on('init', function(content){
infoInit = JSON.parse(content);
channelName = 'init' + infoInit.uid;
channelId = infoInit.channelId;
if (messages[channelId]) {
lastMessages = messages[channelId].slice(Math.max(messages[channelId].length - 5, 1));
for (var i = 0, len = lastMessages.length; i < len; i++) {
io.emit(channelName, JSON.stringify(lastMessages[i][0]));
}
}
});
});
http.listen(port, function(){
console.log('listening on *:' + port);
});